[英]How to build query for relating parent document's field to embedded array document's field. Using MongoDB aggregation Operators
考虑以下名为“ CityAssociation”的集合中的文档
{
"_id" : "MY_ID",
"ThisCityID" : "001",
"CityIDs" : [{
"CityID" : "001",
"CityName" : "Bangalore"
}, {
"CityID" : "002",
"CityName" : "Mysore"
}],
"CityUserDetails": {
"User" : "ABCD"
}
}
现在,我具有User
值,即在上述情况下,我具有值ABCD
并希望仅在第一级的字段ThisCityID
与嵌入式数组documnet的字段CityID
匹配的城市中找到它。 最后,我需要按如下方式进行投影(对于上述情况):
{
'UserName': 'ABCD',
'HomeTown':'Bangalore'
}
在Node.js + MongoDB本机驱动器中,我编写了一个聚合查询,如下所示,该查询无法正常工作。
collection.aggregate([
{ $match: { 'CityUserDetails.User': 'ABCD', 'CityIDs': { $elemMatch: { CityID: ThisCityID}}} },
{ $unwind: "$CityIDs" },
{ $group: {
_id: '$_id',
CityUserDetails: { $first: "$CityUserDetails" },
CityIDs: { $first: "$CityIDs" }
}
},
{ $project: {
_id: 0,
"UserName": "$CityUserDetails.User",
"HomeTown": "$CityIDs.CityName"
}
}
], function (err, doc) {
if (err) return console.error(err);
console.dir(doc);
}
);
谁能告诉我如何使用查询来完成。
注意:在MongoDB模式上,我们无权对其进行更改。
您可以使用$eq
运算符检查第一级的字段ThisCityID与嵌入式数组文档的字段CityID是否匹配。
db.city.aggregate([
{ $match : { "CityUserDetails.User" : "ABCD" }},
{ $unwind : "$CityIDs" },
{ $project : {
matches : { $eq: ["$CityIDs.CityID","$ThisCityID"]},
UserName : "$CityUserDetails.User",
HomeTown : "$CityIDs.CityName"
}},
{ $match : { matches : true }},
{ $project : {
_id : 0,
UserName : 1,
HomeTown : 1
}},
])
结果是:
{
"result" : [
{
"UserName" : "ABCD",
"HomeTown" : "Bangalore"
}
],
"ok" : 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.