[英]How to build query for relating parent document's field to embedded array document's field. Using MongoDB aggregation Operators
Consider the following document in the collection named 'CityAssociation' 考虑以下名为“ CityAssociation”的集合中的文档
{
"_id" : "MY_ID",
"ThisCityID" : "001",
"CityIDs" : [{
"CityID" : "001",
"CityName" : "Bangalore"
}, {
"CityID" : "002",
"CityName" : "Mysore"
}],
"CityUserDetails": {
"User" : "ABCD"
}
}
Now I have User
value ie in above case I have value ABCD
and want to find it with only city where the first level's field ThisCityID
matches to the embedded array documnet's field CityID
. 现在,我具有
User
值,即在上述情况下,我具有值ABCD
并希望仅在第一级的字段ThisCityID
与嵌入式数组documnet的字段CityID
匹配的城市中找到它。 Finally I need to project as follows (for the above case): 最后,我需要按如下方式进行投影(对于上述情况):
{
'UserName': 'ABCD',
'HomeTown':'Bangalore'
}
In Node.js + MongoDB native drive, I wrote a aggregation query as follows which is not working as expected. 在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);
}
);
Can anyone tell me how this can be done with query. 谁能告诉我如何使用查询来完成。
Note: On MongoDB schema we don't have control to change it. 注意:在MongoDB模式上,我们无权对其进行更改。
You can use the $eq
operator to check if the first level's field ThisCityID matches embedded array document's field CityID. 您可以使用
$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
}},
])
And the result is: 结果是:
{
"result" : [
{
"UserName" : "ABCD",
"HomeTown" : "Bangalore"
}
],
"ok" : 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.