Home > other >  mongoose filter collection based on another collection
mongoose filter collection based on another collection

Time:11-09

Author collection

[
   {
      "_id":"asdasd2dqdfwefwe",
      "books":[
         "ISBN2e242",
         "ISBNasdasdasd"
      ]
   },
   {
      "_id":"asdasd2dqdfwefwe",
      "books":[
         "ISBN2e242",
         "ISBN1111sdasd"
      ]
   }
]

Q1. How I can get flat array of all unique ISBN using mongoose query? Should return ['ISBN2e242','ISBNasdasdasd','ISBN1111sdasd']

If there's another collection books,

[
   {"ISBN":"ISBN2e242", "title":"some book1"},
   {"ISBN":"ISBN2e299", "title":"some book2"},
   {"ISBN":"ISBN1111sdasd", "title":"some book3"},
   {"ISBN":"ISBN2e242", "title":"some book4"},
   {"ISBN":"ISBNasdasdasd", "title":"some book5"}, 
]

Q2. How can I get only those books for which ISBN resulted in Q1.? Can these two operations be merged in 1 query or aggregation?

CodePudding user response:

First question:

Use $unwind to deconstruct the array books and $group using $addToSet to avoid repeated values.

yourAuthorCollection.aggregate([
  {
    "$unwind": "$books"
  },
  {
    "$group": {
      "_id": null,
      "books": {
        "$addToSet": "$books"
      }
    }
  }
])

Example here

Second question:

Add a $lookup stage like this:

{
  "$lookup": {
    "from": "books",
    "localField": "books",
    "foreignField": "ISBN",
    "as": "books"
  }
}

As the last books output was an array with all ISBNs you can join the collection with books.

Example here

  • Related