1

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.

6
  • Try this db.collection.aggregate([ { $project: { reserve: { $filter: { input: "$reserve", cond: { $in: [ "$$this", [ 1, 2 ] ] } } } } } ]) Commented Oct 14, 2018 at 16:51
  • I want to use findOne because I am using updateOne for updating data. Commented Oct 14, 2018 at 16:53
  • I am using updateOne for updating data not clear what you are asking Commented Oct 14, 2018 at 16:55
  • 1
    Try this db.collection.updateOne({ row: "A", reserve: { $all: arr } }) Commented Oct 14, 2018 at 17:02
  • 1
    Thnx it works.. Commented Oct 14, 2018 at 17:04

2 Answers 2

2

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 }})
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Hope this helps !!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.