如何建立将父文档字段与嵌入式数组文档字段相关的查询.使用MongoDB聚合运算符 [英] How to build query for relating parent document's field to embedded array document's field. Using MongoDB aggregation Operators

查看:71
本文介绍了如何建立将父文档字段与嵌入式数组文档字段相关的查询.使用MongoDB聚合运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下名为"CityAssociation"的文档中的文档

Consider the following document in the collection named 'CityAssociation'

{
  "_id" : "MY_ID",
  "ThisCityID" : "001",
  "CityIDs" : [{
      "CityID" : "001",
      "CityName" : "Bangalore"
    }, {
      "CityID" : "002",
      "CityName" : "Mysore"
    }],
   "CityUserDetails": {
       "User" : "ABCD"
   }
}

现在我具有User值,即在上述情况下,我具有值ABCD,并希望仅在第一级字段ThisCityID与嵌入式数组documnet的字段CityID相匹配的城市中找到它.最后,我需要按如下方式进行投影(对于上述情况):

Now I have User value i.e. 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. Finally I need to project as follows (for the above case):

{
'UserName': 'ABCD',
'HomeTown':'Bangalore'
}

在Node.js + MongoDB本机驱动器中,我编写了一个聚合查询,如下所示,该查询无法正常工作.

In Node.js + MongoDB native drive, I wrote a aggregation query as follows which is not working as expected.

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.

注意:在MongoDB模式上,我们无权对其进行更改.

Note: On MongoDB schema we don't have control to change it.

推荐答案

您可以使用 $eq 运算符,以检查第一级的字段ThisCityID与嵌入式数组文档的字段CityID是否匹配.

You can use the $eq operator to check if the first level's field ThisCityID matches embedded array document's field 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
}

这篇关于如何建立将父文档字段与嵌入式数组文档字段相关的查询.使用MongoDB聚合运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆