我有一个看起来像这样的文档:
{
"_id" : "AouRpb5g2WR9sZe5z",
"participants" : [
{
"user" : "CYvApwRFADveqBqEY",
"unread" : false
},
{
"user" : "sgoinZkaHbqth8nPr",
"unread" : false
}
],
"createdAt" : ISODate("2016-07-23T04:06:53.748Z")
}
我需要能够找到同时包含用户 'CYvApwRFADveqBqEY'
和 'sgoinZkaHbqth8nPr'
的文档。我能够使用 elemMatch
找到其中一位用户的所有文档,但无法同时找出这两个用户,或者这是否是正确的方法。
最佳答案
使用带有 $all
的 find
查询,你可以这样做:
db.device.find({
"participants.user": {
$all: ["CYvApwRFADveqBqEY", "sgoinZkaHbqth8nPr"]
}
});
来自 $all
的文档:
The $all operator selects the documents where the value of a field is an >array that contains all the specified elements.
关于MongoDB - 通过数组中多个对象的相同字段查询文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545466/