mongodb 如何编写 Mongo 查询以查找具有条件的子文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15081463/
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
How to write Mongo query to find sub document with condition
提问by siva
I have a document in a collection like this, I need to find the record with form_Id:1 and Function_Id:2, how to write the mongo query.
我在这样的集合中有一个文档,我需要找到带有 form_Id:1 和 Function_Id:2 的记录,如何编写 mongo 查询。
"Form_Id" : 1,
"Function" : [{
"Function_Id" : 1,
"Role" : [{
"Role_Id" : 1,
"UserId" : ["Admin", "001"]
}]
}, {
"Function_Id" : 2,
"Role" : [{
"Role_Id" : 2,
"UserId" : ["Admin", "005"]
}]
}]
回答by JohnnyHK
回答by ann
Since your function key is an array, in order to use the $match operator, first you have to use the $unwind operator. http://docs.mongodb.org/manual/reference/aggregation/unwind/And then you use $match operator to find the documents that you want http://docs.mongodb.org/manual/reference/aggregation/match/
由于您的功能键是一个数组,为了使用 $match 运算符,首先您必须使用 $unwind 运算符。http://docs.mongodb.org/manual/reference/aggregation/unwind/然后你使用 $match 运算符来查找你想要的文档http://docs.mongodb.org/manual/reference/aggregation/match/
So your query should look like this
所以你的查询应该是这样的
db.collection.aggregate([{$unwind:"$Function"},{$match:{"Form_id":1,"Function.Function_id":2}}])
By default mongo will display the _id of the document. So if you do not want to display the _id, after matching the relevant ones, you could use the $project operator http://docs.mongodb.org/manual/reference/aggregation/project/
默认情况下,mongo 将显示文档的 _id。所以如果你不想显示_id,在匹配相关的之后,你可以使用 $project 操作符http://docs.mongodb.org/manual/reference/aggregation/project/
db.collection.aggregate([{$unwind:"$Function"},{$match:{"Form_id":1,"Function.Function_id":2}},{$project:{"_id":0,"Form_id":1,"Function":1}}])
If you don't want the form_id to be displayed, simply don't specify the form_id in the project part of the query. By default mongo will only display the keys whose value is 1. If the key is not mentioned it will not display it.
如果您不想显示 form_id,只需不要在查询的项目部分指定 form_id。默认情况下,mongo 只会显示值为 1 的键。如果未提及该键,则不会显示它。
db.collection.aggregate([{$unwind:"$Function"},{$match:{"Form_id":1,"Function.Function_id":2}},{$project:{"_id":0,"Function":1}}])