Serhiy
Serhiy

Reputation: 1981

How to check if Object is NOT in array in mongoDb?

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.

Upvotes: 3

Views: 4249

Answers (3)

Rafiq
Rafiq

Reputation: 11465

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

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

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}}})

Upvotes: 5

kbariotis
kbariotis

Reputation: 802

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 } }
)

Upvotes: 0

Related Questions