ambrs
ambrs

Reputation: 87

How to insert subdocument into array field only if there's no document with the same "key": "value" pair (MongoDB)?

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

Answers (1)

Tom Slabbaert
Tom Slabbaert

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.

Mongo Playground

Upvotes: 1

Related Questions