MongoDB/Mongoose One-to-Many 参考 child 中的 parent - 分组并加入

MongoDB/Mongoose One-to-Many with refence to parent in child - group and join

我按照 Mongo 文档中的建议将 Parent 和 Child collection 参考 child 中的 parent collection 因为 child collection 有成长的前景。 https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

出版商(Parent)Collection:

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

图书(Child)Collection - 参考其中的出版商:

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

现在我想要实现的目标是让所有出版商拥有 sub-array 本书:

    {
  "_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") 如果我在出版商中存储了一系列书籍参考 - 我不想这样做这样做,因为书籍会不断增加。我想知道如何通过书籍 collection.

中出现的出版商参考来获得相同的结果

您必须使用 $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"
                }
        ]
}