Reputation: 87
I have a collection of documents that look like this:
{
"AAA": 1,
"BBB": [
{
"CCC": 1,
"DDD": [1,2,3]
}
]
}
How to insert a new subdocument ({"CCC": 1, "DDD": []}
) into "BBB" array only if there's no object with {"CCC": 1} key pair?
Upvotes: 1
Views: 43
Reputation: 22296
You can actually do this in a couple of ways, the easiest would be to make the query 'fail' to match if the document has CCC: 1
, like so:
db.collection.updateOne(
{
_id: docId,
'BBB.CCC': {
$ne: 1,
},
},
{
'$push': {
BBB: {
'CCC': 1,
'DDD': [],
},
},
},
);
Now if the document has a BBB.CCC
value of 1 then the update will not find a document to update and nothing will be updated as you expect.
Upvotes: 1