canmustu
canmustu

Reputation: 2639

How to pull an object from array in MongoDB

I have pull friend request when it is accepted or canceled. So, when I try to pull it from array, it doesn't work.

It matches for 1 document but 0 document modified.

When I delete the requested_at field from user field, it works well.

Where do I make mistake at ?

MongoDB Document

{
    "_id" : ObjectId("5cb18680aa024b2d441f93cc"),
    "friends" : [],
    "friend_requests" : [ 
        {
            "user" : {
                "id" : ObjectId("5cb14fd7db537905c89e0a72"),
                "requested_at" : ISODate("2019-04-14T17:51:00.588Z")
            }
        }
    ]
}

MongoDB Query

db.getCollection('users').updateOne(
    { _id: ObjectId("5cb18680aa024b2d441f93cc") },
    {
        $pull: {
            friend_requests: {
                user: {
                    id: ObjectId("5cb14fd7db537905c89e0a72")
                }
            }
        }
    });

Result

{
    "acknowledged" : true,
    "matchedCount" : 1.0,
    "modifiedCount" : 0.0
}

Upvotes: 1

Views: 140

Answers (1)

mickl
mickl

Reputation: 49945

Use dot notation to specify a condition:

db.users.updateOne(
    { _id: ObjectId("5cb18680aa024b2d441f93cc") },
    {
        $pull: {
            "friend_requests": {
                "user.id": ObjectId("5cb14fd7db537905c89e0a72")
            }
        }
    });

Upvotes: 1

Related Questions