mongodb 获取文档的特定部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5301795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get specific part of document
提问by powderkeg
I'm trying Mongo db and I wonder if it's possible to only get a specific part of a document?
我正在尝试 Mongo db,我想知道是否可以只获取文档的特定部分?
For example I have:
例如我有:
{
"name" : "MongoDB",
"info" : { x : 203, y : 102 }
}
and I only want the content of info
.
我只想要info
.
The closest I found is db.collection.find({}, { info: 1 })
but this returns me { "info" : { x : 203, y : 102 } }
when I only need { x : 203, y : 102 }
.
我找到的最接近的是db.collection.find({}, { info: 1 })
但是{ "info" : { x : 203, y : 102 } }
当我只需要{ x : 203, y : 102 }
.
回答by Lucas Zamboulis
You could do
你可以做
db.collection.find({},{'info.x':1, 'info.y':1})
but that means listing each and every item of the info object in the projection - which may or may not be what you're looking for.
但这意味着在投影中列出 info 对象的每一项 - 这可能是也可能不是您正在寻找的。
回答by Alex Gorbunov
You can use distinct()
function that resembles by following:
您可以使用distinct()
类似于以下的功能:
db.collection.distinct("info", {info : {$exists : true}})
回答by Scott Hernandez
No, you cannot return just the values for x/y; even if you limit the fields the outer structure is still returned.
不,您不能只返回 x/y 的值;即使您限制字段,仍会返回外部结构。
See Result Projectionsfor more info.
有关更多信息,请参阅结果预测。
回答by devendra tata
read this
读这个
in this,If you specify no projection, the find() method returns all fields of all documents that match the query.
在此,如果指定不投影,则 find() 方法返回与查询匹配的所有文档的所有字段。
回答by hecnabae
You can use aggregation framework:
您可以使用聚合框架:
- $match phase (optional) to filter result.
$project phase to select fields
db.getCollection('yourCollection').aggregate([ {$match:{_id:ObjectId("566fc97f5b79dff1a73ca2ae")}}, {$project:{_id:0, "x":"$info.x", "y":"$info.y"}} ])
- $match 阶段(可选)过滤结果。
$project 阶段选择字段
db.getCollection('yourCollection').aggregate([ {$match:{_id:ObjectId("566fc97f5b79dff1a73ca2ae")}}, {$project:{_id:0, "x":"$info.x", "y":"$info.y"}} ])
回答by Xavier Guihot
Starting
Mongo 4.2
, the$replaceWith
aggregation operator can be used to replace a document by another (in our case by a sub-document):// { name: "MongoDB", info: { x: 203, y: 102 } } db.collection.aggregate({ $replaceWith: "$info" }) // { "x" : 203, "y" : 102 }
Prior to
Mongo 4.2
and startingMongo 3.4
,$replaceRoot
can be used in place of$replaceWith
:db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })
从 开始
Mongo 4.2
,$replaceWith
聚合运算符可用于将文档替换为另一个文档(在我们的示例中为子文档):// { name: "MongoDB", info: { x: 203, y: 102 } } db.collection.aggregate({ $replaceWith: "$info" }) // { "x" : 203, "y" : 102 }
之前
Mongo 4.2
和开始Mongo 3.4
,$replaceRoot
可以用来代替$replaceWith
:db.collection.aggregate({ $replaceRoot: { newRoot: "$info" } })