![](/img/trans.png)
[英]MongoDB - Find document in which array contains any items in query array
[英]MongoDB - Find and return all the items of an array in each document
所以我有一个用户可以在其中输入标签的系统,但是我想添加来自数据库中所有先前标签的动态数据的建议/自动完成功能。
数据如下所示:
collection = [
{
title: "Avengers",
tags:["si-fi", "powers", "super-heroes", "iron-man"],
...
},
{
title: "Lego Movie"
tags:["spider-man", "bottle", "man of steel"],
...
}
...
]
因此,我想检索所有与搜索字符串匹配的标签的数组。
例如,如果我搜索'man'
,我希望返回的数据为:
[
"iron-man",
"spider-man",
"man of steel"
]
我认为无法通过直接查询来完成。 以下聚合可以做到,
db.collection.aggregate([{
$unwind: '$tags'
}, {
$match: {
'tags': { $regex: 'man' }
}
}, {
$group: {
_id: null,
tags: { '$addToSet': '$tags' }
}
}]);
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.