0

Given the following document inside Mongo:

{ 
    "_id" : ObjectId("5d5e9852b2b803bfc66e74a6"), 
    "name" : "NAME", 
    "collection1" : [ 
        { "type" : "TYPE", "collection2" : [ ] } 
    ] 
}

I would like to add elements in the collection2 attribute. I am using the mongo console.

I tried using this query:

db.mycollection.updateOne(
{"name": "NAME"}, 
{$addToSet: {"collection1.$[element].collection2" : { $each: ["a", "b", "c"]}}}, 
{arrayFilters: [{element: 0}]}
);

I also tried to use push, but with no success.

The console returns:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }

2 Answers 2

1

The update didn't update the document because the arrayFilters clause did not match the document. Specifically, your example is filtering on an element in collection1 that is defined as 0, which does not exist.

Changing the update to filter on collection2 being an empty array should result in the update working as expected:

db.test.insert({
...     "_id" : ObjectId("5d5e9852b2b803bfc66e74a6"),
...     "name" : "NAME",
...     "collection1" : [
...         { "type" : "TYPE", "collection2" : [ ] }
...     ]
... })

db.test.update(
... { name: "NAME" },
... { "$addToSet": { collection1.$[element].collection2: { "$each" : [ "a", "b", "c" ] } } },
... { arrayFilters: [ { element.collection2: [ ] } ] }
... )

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.test.find()
{ "_id" : ObjectId("5d5e9852b2b803bfc66e74a6"), "name" : "NAME", "collection1" : [ { "type" : "TYPE", "collection2" : [ "a", "b", "c" ] } ] }
Sign up to request clarification or add additional context in comments.

Comments

1

If you know the index of collection1 element you can omit arrayFilters and just use the index

db.mycollection.updateOne(
    { "name": "NAME" }, 
    { $addToSet: { "collection1.0.collection2": { $each: ["a", "b", "c"] }}}
);

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.