简体   繁体   English

如何使用MongoDB使用具有多个关联的查询执行查询

[英]How to execute a query with a `has many` association using MongoDB

I have a setup with Node, Express, and using backbone. 我使用Node,Express并使用骨干网进行了设置。 Everything works fine and I'm able to retrieve records from by MongoDB collections when they are simple as in getting employees by id or all employees. 一切正常,我可以通过MongoDB集合从记录中检索记录,就像按ID或所有员工获取员工一样简单。 What I'm having trouble understanding is how to get collections from MongoDB that require a more complex query syntax like the following: 我无法理解的是如何从MongoDB获取需要更复杂查询语法的集合,如下所示:

db.employees.aggregate(
   [
     { $group : { _id : "$managerName", employees: { $push: "$fullName" } } }
   ]
)

I currently have the following syntax for extracting the data I want to expose as a json object and bind to the elements in my html page. 我目前有以下语法,用于提取要作为json对象公开的数据并绑定到html页面中的元素。

exports.findById = function(req, res) {
    var id = parseInt(req.params.id);
    db.collection('employees', function(err, collection) {
        collection.findOne({'id': id}, function(err, item) {
            res.jsonp(item);
        });
    });
};

I want to get a list of all Managers and they employees that report to them and then somehow bind this result set to individual divs that would list a Manager as the List heading, and then all the employees that report to them as list items. 我想获取所有经理的列表,并向他们报告的雇员,然后以某种方式将此结果集绑定到将div列为“列表”标题的各个div,然后将所有向他们报告的雇员作为列表项。 The result set will essentially consist of parents and childs. 结果集将基本上由父母和孩子组成。 I want to do this dynamically using backbonejs. 我想使用骨干js动态地做到这一点。

Would I be doing something like 我会做类似的事情吗

exports.findRelations = function(req, res) {
    db.collection('employees', function(err, collection) {
        collection.aggregate({ $group : { _id : "$managerName", employees:{$push: "$fullName" } } }, function(err, item) {
            res.jsonp(item);
        });
    });
};

The aggregation pipeline for MongoDB requires that you pass the operations in an Array. MongoDB的聚合管道要求您在Array中传递操作。 This means the correct query would be: 这意味着正确的查询将是:

db.collection('employees').aggregate([
    { $group : { _id : "$managerName", employees:{$push: "$fullName" } }
  ])
  .toArray(function(err, managers){
    if (err){
      throw err;
    }

    res.jsonp(managers);
  });

You'll find details for using the aggregation pipeline with the NodeJS MongoDB driver here: https://docs.mongodb.org/getting-started/node/aggregation/ 您可以在此处找到有关将聚合管道与NodeJS MongoDB驱动程序结合使用的详细信息: https : //docs.mongodb.org/getting-started/node/aggregation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM