[英]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. 我的MongoDB集合包含一些文档,每个文档都可以包含一系列子文档。 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? 如何告诉MongoDB为集合中的每个子文档生成唯一值?
I'm using the C# MongoDB driver. 我正在使用C#MongoDB驱动程序。
{
_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. MongoDB本身不会为您执行此操作,但是您可以执行许多文档映射器对子文档所做的操作,并在保存它们之前为其分配ObjectId
值。 This will get you a new, and unique-enough value for each of those fields from the C# driver: 对于C#驱动程序中的每个字段,这将为您提供一个新的且唯一的值:
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. 它很容易为您完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.