简体   繁体   中英

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
}

Use dot notation to specify a condition:

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

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