[英]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.