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
ObjectIdvalues before you save them. This will get you a new, and unique-enough value for each of those fields from the C# driver: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.