Rupesh
Rupesh

Reputation: 890

Check if all elements present in an array

I am trying to find whether all elements of the array are found inside an array in a MongoDB database using mongoose.

If my data in MongoDB is -

{
  row: "A",
  reserve: [1,2,3]
}

and if my query data is -

{
  row: "A",
  arr: [1,2] // I want it to return result
}

and if my query data is

{
  row: "A",
  arr: [1,2,4] // I want it to return null
}

I want to update the data but it is updating every time

Reserved.updateOne({row: "A", reserve: {$in: arr}, {
  $push: {
    reserve: arr
  }
}, (err, result) => {
  // ...
});

Please help me.

Upvotes: 1

Views: 79

Answers (2)

Ashh
Ashh

Reputation: 46481

You can use $all operator to match all the elements from the array.

From the docs

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

db.collection.updateOne({ "row": "A", "reserve": { "$all": array }})

or even with find query

db.collection.find({ "row": "A", "reserve": { "$all": array }})

Upvotes: 2

vizsatiz
vizsatiz

Reputation: 2173

You can use the $all operator (link). Something like:

db.collection.updateOne(
        {
          row: "A",
          reserve: { $all: array } 
        }
)

Hope this helps !!

Upvotes: 0

Related Questions