Ankit
Ankit

Reputation: 1011

How to remove object from an Array which is under an object Mongodb

I have a data set like this:

{
    "_id" : ObjectId("5bacc98431481e0520856df8"),
    "action" : {
        "count" : 0,
        "shop" : [ 
            {
                "uid" : ObjectId("5c0b396a50b8a627c4172a2b"),

            }, 
            {
                "uid" : ObjectId("5c0b3b471ed11f2124e1e3a8"),

            },
            {
                "uid" : ObjectId("5c0b3b471ed11f2124e1e3a9"),

            }
         ]
      }
}

How will I remove the above object whose uid is ObjectId("5c0b3b471ed11f2124e1e3a8") through mongodb Query?

I used with the approach which is not perfect according to me. My approach is like this:

db.CollectionName.find({_id: ObjectId("5bacc98431481e0520856df8")})
.then(data => {
  if (data.length > 0) {
        let xData = data[0].notifications.shop;
        let xuid = ObjectId("5c0b3b471ed11f2124e1e3a8");
        let filterData = xData.filter(
          x => x.uid!= xuid
        );
        User.update(
          { _id: ObjectId("5bacc98431481e0520856df8")},
          {
            $set: {
              action: { shop: filterData }
            }
          }
        )
        .then(usr => {
          console.log("deleted successfully")
         })
         .catch(er => {
           console.log(er)
         })
  }
})
.catch(error => {
    console.log(error)
}) 

By this approach I remove the uid from an array which itself under an object. If anyone knows this type of task done through MongoDB Query then please let me know.

Any Help/Suggestion is really appreciated. Thanks in advance for the developer who attempted my Query.

Upvotes: 0

Views: 34

Answers (1)

Akrion
Akrion

Reputation: 18515

The mongo statement to do this would be:

db.getCollection('YOURCOLECTION').update(
{'_id': ObjectId("5bacc98431481e0520856df8")}, 
{ "$pull": 
       { "action.shop": { "uid": ObjectId("5c0b3b471ed11f2124e1e3a8") }} 
})

You would be using $pull command in combination with the $update.

Upvotes: 1

Related Questions