1

Suppose the document as below:

{
  "group_id": 1,
  "group_token": "3bu48xp9ok5",
  "group_passward": "0000",
  "admin": "Forne",
  "member": [
    {
      "mid": 1,
      "Name": "Forne",
      "Email": "[email protected]",
      "Rank": "admin",
      "sub": [
        "test",
        "xxx",
        "Forne"
      ]
    }
  ]
}

Here is my trial:

var collection = myDB.collection('test');
collection.update({"group_token":"3bu48xp9ok5"},{$pull:{"member.$[elem1].sub":"test"}}, {arrayFilters: [{"elem1.Email":"[email protected]"}],multi: true})

How did I update the element with "member.Email":"[email protected]" to make its sub["xxx", "Forne"]

But it prints:

  name: 'MongoError',
  message: 'No array filter found for identifier \'elem1\' in path \'member.$[elem1].sub\'',
  driver: true,
  index: 0,
  code: 2,
  errmsg: 'No array filter found for identifier \'elem1\' in path \'member.$[elem1].sub\'' }

How can I update "sub":[]...?

1 Answer 1

1

You can use $set with $.

db.getCollection('tests').update({
    "group_token":"3bu48xp9ok5", "member.Email" : "[email protected]"
},
{
    "$set": {"member.$.sub": ["hhh", "Cat"]}
})

Before Document:

{
    "_id" : ObjectId("5bd2f41ed79cc5d8b1c62972"),
    "group_id" : 1,
    "group_token" : "3bu48xp9ok5",
    "group_passward" : "0000",
    "admin" : "Forne",
    "member" : [ 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "[email protected]",
            "Rank" : "admin",
            "sub" : [ 
                "test", 
                "xxx", 
                "Forne"
            ]
        }, 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "[email protected]",
            "Rank" : "admin",
            "sub" : [ 
                "test1", 
                "yyyy", 
                "Forte"
            ]
        }
    ]
}

After update document:

{
    "_id" : ObjectId("5bd2f41ed79cc5d8b1c62972"),
    "group_id" : 1,
    "group_token" : "3bu48xp9ok5",
    "group_passward" : "0000",
    "admin" : "Forne",
    "member" : [ 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "[email protected]",
            "Rank" : "admin",
            "sub" : [ 
                "hhhh", 
                "hhhh", 
                "hhhh"
            ]
        }, 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "[email protected]",
            "Rank" : "admin",
            "sub" : [ 
                "test1", 
                "yyyy", 
                "Forte"
            ]
        }
    ]
}
Sign up to request clarification or add additional context in comments.

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.