我是蒙戈查询的新手。我有这条记录,我需要找到具有相同链接的部分。
我的记录:
{
"_id" : ObjectId("1234"),
"name": "singleRecordInMongo",
"__v" : 0,
"sections" : [
{
"name" : "firstElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1161")
},
{
"name" : "secondElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1162")
},
{
"name" : "thirdElement",
"link" : "https://www.other.com",
"_id" : ObjectId("624dd0aca5fb565661da1163")
}
]
}
预期成果:
"sections" : [
{
"times" : 2,
"link" : "https://www.test.com/"
}
]
我尝试过这样的事情,但没有用
db.getCollection('records').aggregate(
{$unwind: "$sections"},
{ $project: {_id: '$_id', value: '$sections'} },
{ $group: {
_id: null,
occurances: {$push: {'value': '$link', count: '$count'}}
}
}
);
编辑: 您可以使用$group
:
db.collection.aggregate([
{$unwind: "$sections"},
{
$group: {
_id: "$sections.link",
orig_id: {$first: "$sections._id" },
count: {$sum: 1 }
}
},
{$match: { "count": {$gt: 1 }}},
{
$group: {
_id: 0,
sections: {$push: { link: "$_id", count: "$count"}}
}
}
])
就像这个游乐场回归:
{
"_id": 0,
"sections": [
{
"count": 2,
"link": "https://www.test.com/"
}
]
}
对于将 JavaScript 函数与$function
运算符一起使用的聚合操作,可以使用哈希映射来跟踪重复项,如下所示:
db.records.aggregate([
{ $addFields: {
sections: {
$map: {
input: "$sections",
in: { times: 1, link: "$$this.link" }
}
}
} },
{ $addFields: {
sections: {
$filter: {
input: {
$function: {
body: function (data) {
const map = {};
data = data.map((item) => {
if (map[item.link]) {
map[item.link].times += item.times
} else {
map[item.link] = item;
}
return item;
});
return data.filter((item) => item !== undefined);
},
args: [ "$sections" ],
lang: "js"
}
},
cond: { $gt: ["$$this.times", 1] }
}
}
} }
])
牢记
在聚合表达式中执行 JavaScript 可能会减少 性能。仅当提供的管道使用
$function
运算符时 运算符无法满足应用程序的需求。
蒙戈游乐场