简体   繁体   中英

Autogenerating values for child/sub-documents in a collection within a MongoDB document

My MongoDB collection has documents that can each contain an array of child documents. Each child document needs a way for me to uniquely identify it so that I can replace it or update it later.

How do I tell MongoDB to generate a unique value for each child document within the set?

I'm using the C# MongoDB driver.

{
    _id: 'gd37dg67dg63782gd78',
    name: 'foo'
    docs: [
        {
            idvalue: 'autogenerated',
            y: 10
        },
        {
            idvalue: 'autogenerated',
            y: 10
        },
        {
            idvalue: 'autogenerated',
            y: 10
        },
    ]
}

MongoDB itself won't do that for you, but you can do what many document mappers do for subdocuments and assign them ObjectId values before you save them. This will get you a new, and unique-enough value for each of those fields from the C# driver:

ObjectId.GenerateNewId()

If you're using a document mapper, look and see how well it supports "nested documents". There's a good chance it will do this for you with little effort.

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