gpt4 book ai didi

Query in MongoDB to return documents matching at least two values in an array(MongoDB中的查询以返回与数组中至少两个值匹配的文档)

转载 作者:bug小助手 更新时间:2023-10-25 11:25:05 25 4
gpt4 key购买 nike



Okay, I've been trying to wrap my head around this for a while and still cannot find the answer. Let's say I have a collection of Mongo documents containing a field with an array of strings called tags.

好吧,我已经想了好一阵子了,但还是找不到答案。假设我有一个Mongo文档集合,其中包含一个带有称为标记的字符串数组的字段。


{
_id: ObjectId("64fdff612ee6d1467c4501f5"),
title: "Document1",
"tags": [
"tagOne"
]
},
{
_id: ObjectId("64fdff612ee6d1467c4501f6"),
title: "Document2",
"tags": [
"tagOne",
"tagTwo"
]
},
{
_id: ObjectId("64fdff612ee6d1467c4501f7"),
title: "Document3",
"tags": [
"tagOne",
"tagTwo",
"tagThree"
]
}

I have no problem returning the documents that contain "tagOne" OR "tagTwo". For example, using

我可以毫不费力地返回包含“tag One”或“tag Two”的文档。例如,使用


db.getCollection("documents").find({ 'tags': { $in: ['tagOne',tagTwo'] }})

Db.getCollection(“Documents”).find({‘tag’:{$in:[‘tag One’,tag Two‘]})


would return all three documents. However, I'm seeking to query for documents that contain at least those two tags. Therefore, a query that would only return the last two documents since they contain at least those two tags (but could contain any other tags as well).

会退还所有三份文件。但是,我正在寻求查询至少包含这两个标记的文档。因此,只返回最后两个文档的查询,因为它们至少包含这两个标记(但也可以包含任何其他标记)。


更多回答
优秀答案推荐

Try with $all which is like an $and: https://www.mongodb.com/docs/manual/reference/operator/query/all/#mongodb-query-op.-all

尝试使用类似于$AND:https://www.mongodb.com/docs/manual/reference/operator/query/all/#mongodb-query-op.-all的$ALL


db.getCollection("documents").find({ 'tags': { $all: ['tagOne','tagTwo'] }})

更多回答

That's what I was looking for! Thank you

这就是我要找的!谢谢你

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com