如何将单个收集的多个文档合并到一个文档中?

时间:2018-03-10 16:06:38

标签: mongodb mongoose mongodb-query one-to-many

我在单个Collection中有多个文档,我遵循Model One-to-Many Relationships with Document References模式来存储数据。但我没有想到聚合来获得预期的结果 其中一个样本如下; -

 /* 1 */
{
   "_id" : ObjectId("5aa3c47d98d91b1148f45895"), 
   "published" : "true", 
   "author" : "acacac",
    "postURL" : "main-post",
   "artId" : "123",
    "mainId" : "earth", 
   "date" : ISODate("2017-11-19T08:00:00.000Z")  
}

 /* 2 */
{   "_id" : ObjectId("5aa3c58e9f139f0880e3c78d"), 
    "body" : "main body part -1",
     "contentTitle" : "title-1",
    "contentCategory" : "category-1",
    "readingId" : "earth"
}
 /* 3 */
{
   "_id" : ObjectId("5aa3c58e9f139f0880e3c78d"), 
    "body" : "main body part -2",
    "contentTitle" : "title-2",
    "contentCategory" : "category-2",
    "readingId" : "earth"
}
 /* 4 */
{
   "_id" : ObjectId("5aa3c5c89f139f0880e3c78e"),
   "ans" : "ans 1",
   "question" : "this is the first q ?", 
   "quizId" : "earth" 
}
 /* 5 */
{
   "_id" : ObjectId("5aa3c5c89f139f0880e3c78e"),
   "ans" : "ans 2",
   "question" : "this is the second q ?", 
   "quizId" : "earth"  
}
 ..
 ..

 etc

我尝试了一些聚合方法但是我找不到解决方案我跟随键值作为常见的

 "mainId" : "earth",
 "readingId" : "earth"
 "quizId" : "earth"

如何获得输出如下: -

 {
   "_id" : ObjectId("5aa3c47d98d91b1148f45895"),
    "published" : "true", 
    "author" : "acacac",
    "postURL" : "main-post",
    "artId" : "123",
    "mainId" : "earth", 
    "date" : ISODate("2017-11-19T08:00:00.000Z"),

   "content1" : [
            /* 2 */
         {  "body" : "main body part -1",
            "contentTitle" : "title-1",
            "contentCategory" : "category-1" },      
            /* 3 */
         {  "body" : "main body part -2",
            "contentTitle" : "title-2",
            "contentCategory" : "category-2" }                  
   ],
   "content2" : [
        /* 4 */
       {   "question" : "this is the first q ?",    
           "ans" : "ans 1" },

        /* 5 */
         {  "question" : "this is the second q ?", 
            "ans" : "ans 2"  }
   ]
}
..
..
. etc

1 个答案:

答案 0 :(得分:1)

您可以使用$ lookup。它类似于SQL-outerjoin。

尝试:

db.getCollection('tableName').aggregate([
{$match:{"mainId":{$exists:true}}}
,
{
   $lookup:
     {
       from: 'tableName',
       localField: 'mainId',
       foreignField: 'readingId',
       as: "content1"
     }
}
,
{
   $lookup:
     {
       from: 'tableName',
       localField: 'mainId',
       foreignField: 'quizId',
       as: "content2"
     }
}
])

其中tableName是表的名称。