MongoDB / Mongoose一对多,对孩子的父母有依据 - 群组和加入

时间:2017-04-09 14:34:29

标签: mongodb mongoose mongodb-query mongoose-populate

我遵循Mongo文档中有关Parent& amp;将子集合中的父集合作为子集合的子集合具有增长的前景。 https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

出版商(家长)收藏:

{
   _id: "oreilly",
   name: "O'Reilly Media",
   founded: 1980,
   location: "CA"
}

书籍(儿童)收藏 - 参考其中的出版商:

{
   _id: 123456789,
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher_id: "oreilly"
},{
   _id: 234567890,
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly"
}

现在我想要实现的是让所有出版商都拥有一系列图书:

    {
  "_id": "oreilly",
  "name": "O'Reilly Media",
  "founded": 1980,
  "location": "CA",
  "books": [
    {
      "_id": 123456789,
      "title": "MongoDB: The Definitive Guide",
      "author": [
        "Kristina Chodorow",
        "Mike Dirolf"
      ],
      "published_date": "2010-09-24",
      "pages": 216,
      "language": "English",
      "publisher_id": "oreilly"
    },
    {
      "_id": 234567890,
      "title": "50 Tips and Tricks for MongoDB Developer",
      "author": "Kristina Chodorow",
      "published_date": "2011-05-06",
      "pages": 68,
      "language": "English",
      "publisher_id": "oreilly"
    }
  ]
}

我使用Mongoose,&我知道如果我在出版商中存储了一系列图书参考资料,我可以完成.populate(" books") - 我不想这样做,因为图书会不断增加。我想知道如何在书籍集合中出现发布商参考的同一结果。

1 个答案:

答案 0 :(得分:3)

您必须使用$lookup来执行加入。

db.publisher.aggregate([{$lookup: {from: 'books', localField: '_id', foreignField: 'publisher_id', as: 'books'}} ]).pretty()
{
        "_id" : "oreilly",
        "name" : "O'Reilly Media",
        "founded" : 1980,
        "location" : "CA",
        "books" : [
                {
                        "_id" : 123456789,
                        "title" : "MongoDB: The Definitive Guide",
                        "author" : [
                                "Kristina Chodorow",
                                "Mike Dirolf"
                        ],
                        "published_date" : ISODate("2010-09-24T00:00:00Z"),
                        "pages" : 216,
                        "language" : "English",
                        "publisher_id" : "oreilly"
                },
                {
                        "_id" : 234567890,
                        "title" : "50 Tips and Tricks for MongoDB Developer",
                        "author" : "Kristina Chodorow",
                        "published_date" : ISODate("2011-05-06T00:00:00Z"),
                        "pages" : 68,
                        "language" : "English",
                        "publisher_id" : "oreilly"
                }
        ]
}