嵌套数组中
问题描述:
搜索多个值,我有以下集合:嵌套数组中
{
_id: 1,
docs: [{
name: file1,
labels: [label1, label2, label3, label4]
},{
name: file2,
labels: [label3, label4]
},{
name: file3,
labels: [label1, label3, label4]
}]
}
当标签用户搜索,我需要得到所有具有这些标签的文档。
因此,如果用户搜索“label1”和“label3”,我需要获得“file1”和“file3”。目前我有以下代码:
var collection = db.collection(req.user.username);
collection.aggregate([
// Unwind each array
{ "$unwind": "$docs" },
{ "$unwind": "$docs.labels" },
// Filter just the matching elements
{
"$match": {
"docs.labels": { "$all": ["label1", "label3"] }
}
}
]).toArray(function (err, items) {
res.send(items);
});
这工作正常,如果我只搜索“label1”或“label3”,但不是两个在一起。你能帮我解决这个问题吗,因为我还没有找到一个适合自己的答案。
答
您可以在$project
阶段通过$filter
高效地完成此项工作。
let inputLabels = ["label1", "label3"];
collection.aggregate([
{ "$match": { "docs.labels": { "$all": inputLabels }}},
{ "$project": {
"docs": {
"$filter": {
"input": "$docs",
"as": "doc",
"cond": { "$setIsSubset": [ inputLabels, "$$doc.labels" ] }
}
}
}}
])]).toArray(function (err, items) {
res.send(items);
});
+0
非常感谢!我自己尝试使用'$ project'和'$ filter',但由于没有完全理解它,我无法得到想要的结果。 – Mathias
你的mongod版本是什么? – styvane
为什么你没有使用'mongoose'模块? –
@Styvane my mongo是3.2.10版本 – Mathias