如何在mongodb中的单个数组中推送所有值

时间:2019-05-09 14:25:55

标签: mongodb mongodb-query aggregation-framework

  

学院

/* 1 createdAt:5/9/2019, 7:00:04 PM*/
{
    "_id" : ObjectId("5cd42b5c65b41027845938ae"),
    "clgID" : "100",
    "name" : "Anna University"
},

/* 2 createdAt:5/9/2019, 7:00:04 PM*/
{
    "_id" : ObjectId("5cd42b5c65b41027845938ad"),
    "clgID" : "200",
    "name" : "National"
}
  

主题:

/* 1 createdAt:5/9/2019, 7:03:24 PM*/
{
    "_id" : ObjectId("5cd42c2465b41027845938b0"),
    "name" : "Hindi",
    "members" : {
        "student" : [
            "123"
        ]
    },
    "college" : {
        "collegeID" : "100"
    }
},

/* 2 createdAt:5/9/2019, 7:03:24 PM*/
{
    "_id" : ObjectId("5cd42c2465b41027845938af"),
    "name" : "English",
    "members" : {
        "student" : [
            "456",
            "789"
        ]
    },
    "college" : {
        "collegeID" : "100"
    }
}

这里我有两个集合,我想加入Colleges表,clgID表,Subjects表,然后我想加入college.collegeID值并根据members.student推入单个数组。

  

我的预期输出

college.collegeID
  

我的代码

{
    "GroupDetails" : [ ],
    "clgName" : "National"
},
{
    "GroupDetails" : [
        "123",
        "456",
        "789"
    ],
    "clgName" : "Anna University"
}
  

我越来越喜欢

db.Colleges.aggregate([
    { $match : { "clgID" : { $in :  ["100", "200"]  } } },
    { $lookup: { from: "Subjects", localField: "clgID", foreignField: "college.collegeID", as: "GroupDetails" } },
    //{ $unwind: "$GroupDetails" },
    { $project: { '_id' : false, 'clgName' : '$name', 'GroupDetails.members.student' : true } }
])

1 个答案:

答案 0 :(得分:1)

您可以在mongodb 3.6 及更高版本

中使用以下聚合
{'1111': ['3456', '6789'], '1122': ['2345', '7890']}

MongoPlayground

或者与mongodb 3.4 及以下版本

一起使用
db.Colleges.aggregate([
  { "$match": { "clgID": { "$in": ["100", "200"] } } },
  { "$lookup": {
    "from": "Subjects",
    "let": { "clgId": "$clgID" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$$clgId", "$college.collegeID"] } } },
      { "$group": {
        "_id": "$college.collegeID",
        "groupDetails": { "$push": "$members.student" }
      }},
      { "$project": {
        "groupDetails": {
          "$reduce": {
            "input": "$groupDetails",
            "initialValue": [],
            "in": { "$concatArrays": ["$$this", "$$value"] }
          }
        }
      }}
    ],
    "as": "clg"
  }},
  { "$unwind": { "path": "$clg", "preserveNullAndEmptyArrays": true } },
  { "$project": {
    "clgName": "$name",
    "groupDetails": { "$ifNull": ["$clg.groupDetails", []] }
  }}
])

MongoPlayground