Mongodb 获取文档的特定部分
我正在尝试Mongo db,我想知道是否可以只获取文档的特定部分 例如,我有:Mongodb 获取文档的特定部分,mongodb,Mongodb,我正在尝试Mongo db,我想知道是否可以只获取文档的特定部分 例如,我有: { "name" : "MongoDB", "info" : { x : 203, y : 102 } } 我只想要info的内容 我找到的最接近的是db.collection.find({},{info:1}),但当我只需要{x:203,y:102}时,它返回我{info:{x:203,y:102}
{
"name" : "MongoDB",
"info" : { x : 203, y : 102 }
}
我只想要info
的内容
我找到的最接近的是db.collection.find({},{info:1})
,但当我只需要{x:203,y:102}
时,它返回我{info:{x:203,y:102}
<
db.collection.find({},{'info.x':1, 'info.y':1})
但这意味着在投影中列出信息对象的每一项-这可能是您想要的,也可能不是您想要的。不,您不能只返回x/y的值;即使您限制了字段,外部结构仍然会返回 有关更多信息,请参阅。您可以使用类似以下功能的
distinct()
函数:
db.collection.distinct("info", {info : {$exists : true}})
读这个
在这种情况下,如果不指定投影,find()方法将返回与查询匹配的所有文档的所有字段。您可以使用:
db.getCollection('yourCollection').aggregate([
{$match:{{u id:ObjectId(“566fc97f5b79dff1a73ca2ae”)},
{$project:{{u id:0,“x”:“$info.x”,“y”:“$info.y”}
])
- 从
开始,可以使用聚合操作符将一个文档替换为另一个文档(在本例中为子文档):Mongo 4.2
- 在
之前和启动Mongo 4.2
之前,可以使用Mongo 3.4
:$replaceWith
db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })
db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })