我有Mongo DB集合,其中包含以下项目:
{
"_id" : ObjectId("123123123123123123"),
"title" : "Item-001",
"tags" : [
"red"
],
}
{
"_id" : ObjectId("234234234234234"),
"title" : "Item-002",
"tags" : [
"red,yellow"
],
}
目的:我想找到有red
标签的物品。在这个例子中,我想同时得到Item-001和Item-002。
What I have try我已经尝试了下面的查询,但它只返回Item-001
。我的目标是得到Item-002
也因为它包含红色标签。我该如何构建我的查询,以便能够同时获得这两个文档?
db.getCollection("items").find({
"tags": { '$in': [ 'red'] },
})
第一个解
您可以使用find()
查询和$regex
操作符:
db.collection.find({
"tags": {
"$regex": "red"
}
})
工作示例
第二方案
你可以使用聚合框架:
$match
with$expr
-基于自定义过滤器 过滤文档$filter
与$regexMatch
-过滤标签并查看它是否至少有一个包含">red的项。"。$size
-获取上述过滤数组的大小。$gt
-检查是否过滤数组至少有一个元素。
db.collection.aggregate([
{
"$match": {
"$expr": {
"$gt": [
{
"$size": {
"$filter": {
"input": "$tags",
"cond": {
"$regexMatch": {
"input": "$$this",
"regex": "red"
}
}
}
}
},
0
]
}
}
}
])
工作示例
您的tags字段是一个数组,但是条目由逗号分隔符连接。这看起来像是一个错误。如果可能的话,你应该改一下。
如果不可能,这里有一个解决方案,将字符串分割成一个列表,然后匹配。
db.collection.aggregate([
{
"$addFields": {
"tagList": {
$split: [
{"$arrayElemAt": ["$tags", 0]}, ","
]
}
}
},
{
$match: {
"tagList": "red"
}
}
])
游乐场