'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.
Solution 1:[1]
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}}})
Solution 2:[2]
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 } }
)
Solution 3:[3]
const a = await Trans.findOneAndUpdate(
{
_id: data.id,
'products.id': { $nin: [product.id] },
},
{
$inc: {
actualCost: product.mrp,
},
$push: {
products: { id: product.id },
},
},
{ new: true }
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sergey Berezovskiy |
| Solution 2 | kbariotis |
| Solution 3 | Rafiq |
