combining two $elemMatch queries with AND boolean operator in MongoDB
我有两个不同的 mongoDB 查询,代表两个不同的条件,例如:
1
|
{ stuff: { $elemMatch: { foo: 1, bar:”a” } } }
|
和:
1
|
{ stuff: { $elemMatch: { foo: 2, bar:”b” } } }
|
其中 stuff 是一个包含 foo 和 bar 字段集的元素数组。
现在,我不确定如何匹配集合中同时满足上述两个条件的元素。
要明确一点:在这种情况下,我需要获取所有元素,这些元素同时具有 stuff 的一个元素,其中 foo 设置为 1 且 bar 设置为 “a” 以及一个stuff 将 foo 设置为 2 而 bar 设置为 “b”.
执行 { stuff: { $elemMatch: { foo: { $in: [1, 2] }, bar: { $in: [“a”,”b”] } } } 是错误的,因为它在两个表达式(包括两个新表达式)上的行为类似于 OR。
你知道如何AND它们吗?
- 不太确定你想要完成什么。 stuff.foo 怎么可能同时等于 1 和 2 呢?只有当 foo 是一个数组时才有可能。在这种情况下,这是 stackoverflow.com/questions/5366687/… 的副本
- @mnemosyn:嗯,也许是这样。谢谢指点! :)
- @mnemosyn:所以,也许是: { stuff: { foo: { $all: [1, 2] } } } ?但是,如果我在 stuff 的元素中有另一个字段,例如 bar 怎么办? (我会更新问题)
Just to be clear: in this case I need to get all elements that have both one element of stuff that has foo set as 1 with bar set as”a” and also one element of stuff that has foo set as 2 with bar set as”b”.
我希望我明白了。那不应该是
1
2 3 |
db.coll.find({ $and: [
{“stuff” : { $elemMatch : {“foo” : 1,”bar” :”a” } } }, {“stuff” : { $elemMatch : {“foo” : 2,”bar” :”b” } } } ]}); |
?
- 有什么方法可以在 $elemMatch 中使用 $and,而不是像这个答案中那样使用其他方式?
来源:https://www.codenong.com/23272682/