简体   繁体   中英

Get ID of object added to inner collection on MongoDB

I have a user collection where each user contains a profile. Each profile can contain a list of email addresses that should be saved for that user. Using MongoDB, I can add an email to that list by doing:

db.users.update_one( {'_id': ObjectId(userid)}, {'$push': {'profile.emails': email.__dict__}} )

This will generate an _id for the email, which I want. However, as far as I can tell, the UpdateResult returned doesn't contain the _id of the newly added item. I know that since email addresses are unique, I could query against that value but I don't think I should have to perform a second request. Is there a way I can request this ID with the update request?

The email payload looks like this:

{
    'address': 'jdoe@fake.email.com',
    'is_primary': true,
    '_id': null
}

and the result of the request (retrieved from the server) is:

emails: [
    {
        'address': 'jdoe@fake.email.com',
        'is_primary': true,
        '_id': ObjectId("5d592f53d3f075f4acfdfab1")
    }
]

To be completely clear, the email dictionary does have a _id field so it's quite possible that it's being populated automatically by MongoDB.

I can't really get my head around the _id generation, it should not be done by MongoDB.

Nevertheless, the findOneAndUpdate with the returnNewDocument option set to true should do the trick. Have a look over there : https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

This will return the full document after being updated.

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