【问题标题】:MongoDB Aggregate - Unwind, group and projectMongoDB Aggregate - 放松、分组和项目
【发布时间】:2014-10-30 03:39:14
【问题描述】:

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

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

当前查询

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


用户

{ "_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
    }
  ]
}

结果

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

提前致谢,尼克

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案1】:

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

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

    如果有多个所有者并且您需要一些优先级,那么您可以在组之前实现 $sort。或者只是 $project 而不是为了吸引所有人而进行分组。

    【讨论】:

    • 感谢您的回答,但这似乎返回了一个空结果。有什么想法吗?
    • 如果每个用户只有一个组织会更简单,那么这是一个明确的考虑因素。
    • @NickPrice Typo “组织”整天都在谈论美国
    • 非常感谢。之前没有使用过$first 运算符。非常感谢!
    猜你喜欢
    • 2021-09-11
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2023-03-04
    • 2020-11-20
    • 2015-06-12
    • 1970-01-01
    相关资源
    最近更新 更多