假设我的收藏中有以下文件:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
Run Code Online (Sandbox Code Playgroud)
查询:
db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)
要么
db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)
返回匹配的文档(文档1),但始终包含所有数组项shapes:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
Run Code Online (Sandbox Code Playgroud)
但是,我想仅使用包含以下内容的数组来获取文档(文档1)color=red:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我有像这样的子文档数组
{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 1
},
{
"a" : 2
},
{
"a" : 3
},
{
"a" : 4
},
{
"a" : 5
}
]
}
Run Code Online (Sandbox Code Playgroud)
我可以过滤子文档> 3
我期待下面的结果
{
"_id" : ObjectId("512e28984815cbfcb21646a7"),
"list" : [
{
"a" : 4
},
{
"a" : 5
}
]
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用$elemMatch但返回数组中的第一个匹配元素
我的查询:
db.test.find( { _id" : ObjectId("512e28984815cbfcb21646a7") }, {
list: {
$elemMatch:
{ a: { $gt:3 }
}
}
} ) …Run Code Online (Sandbox Code Playgroud)