MongoDB聚合 - 展开,分组和项目

时间:2021-01-19 02:54:18

Using the collection Users, is it possible to retrieve the below unique list of organisations/owners? If this current set up isn't possible, is it possible to get the same results from two ID-linked collections with one query?

使用收集用户,是否可以检索以下唯一的组织/所有者列表?如果无法进行当前设置,是否可以通过一个查询从两个ID链接的集合中获得相同的结果?

Currently, using Mongoose I can only retrieve the group of organisation names:

目前,使用Mongoose我只能检索组织名称组:

Current query

当前查询

userModel.aggregate([ { $unwind:'$organisations' } , { $group: { name: '$organisations.name' } } ])

userModel.aggregate([{$ unwind:'$ organizationss'},{$ group:{name:'$ organisations.name'}}])


Users

用户

{ "_id" : ObjectId("53f4a94e7c88310000000001"), 
  "email" : "bob@example.com",
  "organisations" : [
    {
      "name" : "OrgOne", 
      "isOwner" : true
    }
  ]
},
{ "_id" : ObjectId("53f4a94e7c88310000000002"), 
  "email" : "ash@something.com",
  "organisations" : [
    {
      "name" : "OrgOne"
    }
  ]
},
{ "_id" : ObjectId("53f4a94e7c88310000000003"), 
  "email" : "george@hello.com",
  "organisations" : [
    {
      "name" : "OrgTwo", 
      "isOwner" : true
    }
  ]
}

Results

结果

{ "orgName" : "OrgOne", 
  "owner" : 53f4a94e7c88310000000001
},
{ "orgName" : "OrgTwo", 
  "owner" : 53f4a94e7c88310000000003
}

Thanks in advance, Nick

提前谢谢,尼克

1 个解决方案

#1


2  

Seems like an odd use of aggregation to me, but possibly there are several "organisations" per user here, so I guess I'll continue:

对我来说似乎是一种奇怪的聚合使用,但是每个用户可能有几个“组织”,所以我想我会继续:

userModel.aggregate(
    [
        { "$match": { "organisations.isOwner": true } },
        { "$unwind": "$organisations" },
        { "$match": { "organisations.isOwner": true } },
        { "$group": { 
            "_id": "$organisations.name",
            "owner": { "$first": "$_id" }
        }} 
    ],
    function(err,result) {

    }
);

If there is more than one owner and you need some precedence then you can implement a $sort before the group. Or otherwise just $project rather than group in order to get everyone.

如果有多个所有者并且您需要一些优先权,那么您可以在该组之前实现$ sort。或者只是$ project而不是group来获得每个人。

#1


2  

Seems like an odd use of aggregation to me, but possibly there are several "organisations" per user here, so I guess I'll continue:

对我来说似乎是一种奇怪的聚合使用,但是每个用户可能有几个“组织”,所以我想我会继续:

userModel.aggregate(
    [
        { "$match": { "organisations.isOwner": true } },
        { "$unwind": "$organisations" },
        { "$match": { "organisations.isOwner": true } },
        { "$group": { 
            "_id": "$organisations.name",
            "owner": { "$first": "$_id" }
        }} 
    ],
    function(err,result) {

    }
);

If there is more than one owner and you need some precedence then you can implement a $sort before the group. Or otherwise just $project rather than group in order to get everyone.

如果有多个所有者并且您需要一些优先权,那么您可以在该组之前实现$ sort。或者只是$ project而不是group来获得每个人。