Home > front end >  Get document by insertedId MongoDB
Get document by insertedId MongoDB

Time:10-20

I have 2 collections in the mongoDB database: books and authors.

in a book document there is a record of an author from the authors collection.

how can I get the author document By insertedId?

book document example:

_id: new ObjectId("6350f2eaf7dd9bfc16392a19"),
    name: 'the teacher',
    discreption: 'very good book',
    published: '1.1.2022',
    author: {
      acknowledged: true,
      insertedId: new ObjectId("6350f2e9f7dd9bfc16392a17")
    },
    pages: 500
  },

CodePudding user response:

you can populate the author document by

book.find().populate({path: "author.insertedId"}),

else

db.collectionName.find().populate("author.insertedId"),

else

db.book.aggregate([
  {
    "$lookup": {
      "from": "author",
      "localField": "author.insertedId",
      "foreignField": "_id",
      "as": "author"
    }
  }
]

https://mongoplayground.net/p/dSmT3kbwBaV

  • Related