简体   繁体   中英

How to remove elements of an array based on the array element's data in MongoDB

How to write a Mongo query to remove elements of an array if it contain specific data?

{
    "_id": ObjectId("ajdi293akjf83rhfsf398"),
    "one": "oneData",
    "two": [
        {
         "_id":ObjectId("akjf82ijikfj83jkfkj3"),
         "value": 1
        },
        {
         "_id":ObjectId("akjf82ijikfj83jkfkj3"),
         "value": 2
        },
        {
         "_id":ObjectId("akjf82ijikfj83jkfkj3"),
         "value": 1
        }
        ]
}

Need to remove the elements of two if the the elements contains value as 1

{
    "_id": ObjectId("ajdi293akjf83rhfsf398"),
    "one": "oneData",
    "two": [
        {
         "_id":ObjectId("akjf82ijikfj83jkfkj3"),
         "value": 2
        }
        ]
}

Please tell me how to achieve this Many Thanks in advance.

Update command with $pull operator can do the trick.

You can use:

    db.collection.update( {} ,
                          { $pull: {two : {value : 1} } },
                          { multi: true });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM