Node.js 如何建立关联父文档的查询&x27;s字段到嵌入式数组文档';斯菲尔德。使用MongoDB聚合运算符

Node.js 如何建立关联父文档的查询&x27;s字段到嵌入式数组文档';斯菲尔德。使用MongoDB聚合运算符,node.js,mongodb,mongodb-query,Node.js,Mongodb,Mongodb Query,请考虑名为“CityAssociation”的集合中的以下文档 { "_id" : "MY_ID", "ThisCityID" : "001", "CityIDs" : [{ "CityID" : "001", "CityName" : "Bangalore" }, { "CityID" : "002", "CityName" : "Mysore" }], "CityUserDetails": { "

请考虑名为“CityAssociation”的集合中的以下文档

{
  "_id" : "MY_ID",
  "ThisCityID" : "001",
  "CityIDs" : [{
      "CityID" : "001",
      "CityName" : "Bangalore"
    }, {
      "CityID" : "002",
      "CityName" : "Mysore"
    }],
   "CityUserDetails": {
       "User" : "ABCD"
   }
}
现在我有了
User
值,也就是说,在上面的例子中,我有值
ABCD
,并且只想在第一级的字段
ThisCityID
与嵌入式数组documnet的字段
CityID
匹配的城市中找到它。最后,我需要进行如下项目(针对上述情况):

在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);
    }
);
有谁能告诉我如何使用query来实现这一点吗

注意:在MongoDB模式上,我们无法更改它。

您可以使用运算符检查第一级的字段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
}
{
    "result" : [
        {
            "UserName" : "ABCD",
            "HomeTown" : "Bangalore"
        }
    ],
    "ok" : 1
}