在一个问题的答案中,我发现了一个使用$ elemMatch搜索数组值的有趣解决方案.
如果我们的藏品中有以下文件:
{
foo : [ { bar : "xy", baz : 1 },
{ bar : "a", baz : 10 } ]
},
{
foo : [ { bar : "xy", baz : 5 },
{ bar : "b", baz : 50 } ]
}
Run Code Online (Sandbox Code Playgroud)
以下查询仅匹配第一个文档:
db.test.find({
foo : { "$all" : [ { "$elemMatch" : { bar : "xy", baz : 1} }, { "$elemMatch" : { bar : "a", baz : 10 } } …Run Code Online (Sandbox Code Playgroud) 我有一个包含下一个数据的集合:
db.MyCollection.insert({
id: 1,
Location: [ 1, 1 ],
Properties: [ { Type: 1, Value: "a" }, { Type: 2, Value: "b" }, { Type: 3, Value: "c" } ]
});
db.MyCollection.insert({
id: 2,
Location: [ 1, 2 ],
Properties: [ { Type: 1, Value: "a" }, { Type: 2, Value: "a" }, { Type: 3, Value: "c" } ]
});
db.MyCollection.insert({
id: 3,
Location: [ 2, 1 ],
Properties: [ { Type: 1, Value: "a" }, { Type: 3, …Run Code Online (Sandbox Code Playgroud) mongodb ×2