3

I want to push Object in members array, if it's not there. is there way to check if Object is not in array in mongodb?

{
 _id: 1111,
 members:[
 {user_id: 11},
 {user_id: 12},
 {user_id: 13}
 ]
}

So I want to check if:

newUser = {user_id: 14}

is not in members array, if not - push it there. Stuck with it. Thank you in advance for help.

7
  • 1
    You can try db.collection.update( { _id: 1111 }, { $addToSet: { members: {user_id: 14} } } ). This will not do anything if the value is already present. More here docs.mongodb.com/manual/reference/operator/update/addToSet/… Commented Mar 6, 2017 at 15:23
  • thanks will try it Commented Mar 6, 2017 at 15:23
  • @Veeram that will match document with _id: 1111 each time your run this query. And it will try to update document each time Commented Mar 6, 2017 at 15:31
  • @SergeyBerezovskiy I assumed OP's wants to update the doc in question. So query for _id and update using $addToSet. Commented Mar 6, 2017 at 15:34
  • @Veeram might be, but in question OP states 'is there way to check if Object is not in array in mongodb?' And example below also about checking whether newUser is in members array. Commented Mar 6, 2017 at 15:44

3 Answers 3

5

Use $nin operator to check whether members array not contains document with user_id equal to 14. Update is simple $push:

db.collection.update({'members.user_id':{$nin: [14]}}, {$push:{members:{user_id:14}}})
Sign up to request clarification or add additional context in comments.

Comments

0

First, you have to check if the array in the document contains that specific object. Use elemMatch for this

db.collection.find(
   { _id: 1111, members: { $elemMatch: { user_id: 14 } } }
)

Then, if the above returns nothing you pushing the object into

db.collection.update(
   { _id: 1111 },
   { $push: { user_id: 14 } }
)

Comments

0
const a = await Trans.findOneAndUpdate(
            {
              _id: data.id,
              'products.id': { $nin: [product.id] },
            },
            {
              $inc: {
                actualCost: product.mrp,
              },
              $push: {
                products: { id: product.id },
              },
            },
            { new: true }
          );

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.