mongodb - 在 MongoDb 中返回没有其键的对象
问题描述
我正在使用 MongoDb 3.2
假设我在 MongoDb 集合中有这个文档:
{
"_id" : ObjectId("5bad65b9777f6df3ce840fd1"),
"entryCode" : "1234",
"first" : {
"someKey" : "x",
"anotherKey" : "y"
},
"second" : {
"someKey" : "u",
"anotherKey" : "v",
}
}
当我执行以下查询时:
db.collection.find({entryCode:"1234"},{_id:0, first:1})
我得到这个返回的结果:
{
"first" : {
"someKey" : "x",
"anotherKey" : "y"
}
}
但是,我想返回的是:
{
"someKey" : "x",
"anotherKey" : "y"
}
请注意,我不希望键first
成为返回值的一部分。只是里面的对象值。我可以使用什么 Mongo 查询?
解决方案
您需要$replaceRoot运算符,请尝试:
db.col.aggregate([
{ $match: { entryCode:"1234" } },
{
$replaceRoot: {
newRoot: "$first"
}
}
])
编辑:在 MongoDB 3.2 中,您只能$project
明确使用和指定字段:
db.col.aggregate([
{ $match: { entryCode:"1234" } },
{
$project: {
_id: 0,
someKey: "$first.someKey",
anotherKey: "$first.anotherKey",
}
}
])
推荐阅读
- java - 如何添加 Java 8+。在 android 项目中使用 Maven 构建
- javascript - 带有 cron 的 Javascript
- angular - 如何在没有 HammerJS 的情况下使用 Angular Material
- java - 计算数组中最长排序子序列的问题
- angular - 如何修复无法读取 Angular 中未定义的属性
- javascript - 将 Javascript 嵌入批处理文件以清除 Internet Explorer SSL 状态
- python - pandas concat给出无效的BXL错误sql server 2017
- java - 没有找到 void org.opencv.core.Core.rotate_0 的实现
- javascript - 如何最好地使用 React.Fragment
- c# - 在 .Net Core Console App 上为 DateTimeOffset 格式等设置全球文化