Home > Software design >  MongoDb: search only if it contains all ids within the array
MongoDb: search only if it contains all ids within the array

Time:11-17

I am looking for an array of ids, inside another array, the problem is that if it contains at least one "id" it returns the result. The validation should be that it has to have all the "ids" that I am passing.

{ subcategories: { $in: [ ObjectId('61729d550e8fe20011cc57d2', ObjectId('61693f589a34340012b1d5d8'), ObjectId('61693f2c9a34340012b1d5b7') )] } } 

example:

  • subcategories: ["61729d550e8fe20011cc57d2", "61693f2c9a34340012b1d5b7"] -> this one should not appear, because it contains only 2 of the 3 I am looking for

CodePudding user response:

I think you are looking for $all.

The docs says:

The $all operator selects the documents where the value of a field is an array that contains all the specified elements

db.collection.find({
  subcategories: {
    $all: [
      "61729d550e8fe20011cc57d2",
      "61693f589a34340012b1d5d8",
      "61693f2c9a34340012b1d5b7"
    ]
  }
})

Example here

  • Related