好吧,我已经尝试解决这个问题有一段时间了,但仍然找不到答案。假设我有一个 Mongo 文档集合,其中包含一个带有名为 tags 的字符串数组的字段。
{
_id: ObjectId("64fdff612ee6d1467c4501f5"),
title: "Document1",
"tags": [
"tagOne"
]
},
{
_id: ObjectId("64fdff612ee6d1467c4501f6"),
title: "Document2",
"tags": [
"tagOne",
"tagTwo"
]
},
{
_id: ObjectId("64fdff612ee6d1467c4501f7"),
title: "Document3",
"tags": [
"tagOne",
"tagTwo",
"tagThree"
]
}
我可以毫无问题地返回包含“tagOne”OR“tagTwo”的文档。例如,使用
db.getCollection("documents").find({ 'tags': { $in: ['tagOne',tagTwo'] }})
将返回所有三个文档。 但是,我正在寻求查询包含至少这两个标签的文档。因此,查询只会返回最后两个文档,因为它们包含至少这两个标签(但可以包含任何其他标签也是如此)。
尝试使用$all,它就像一个$and:https://www.mongodb.com/docs/manual/reference/operator/query/all/#mongodb-query-op.-all
db.getCollection("documents").find({ 'tags': { $all: ['tagOne','tagTwo'] }})