我的文档结构如下:
{
"_id": <unique id>,
"embeddedDocs":
{
1: {field1: value1,
_creation_timestamp: <time when doc 1 was created>},
2: {field1: value2,
_creation_timestamp: <time when doc 2 was created>}
}
}
我希望嵌入式文档具有&#34;创建时间戳&#34;即,创建嵌入文档的时间。
upsert
因为每次我这样做,_creation_timestamp
都会更新。 setOnInsert
用于_creation_timestamp
,因为我必须使用set
来更新field1
来覆盖_creation_timestamp
。 set
和setOnInsert
因为我收到错误"Cannot update embeddedDocs.1 and embeddedDocs.1._creation_timestamp at the same time"
答案 0 :(得分:0)
为什么要将文档填充到较大文档中的伪数组中?您可以通过将数组中的子文档放入集合的成员中来获益。如果您需要将文档标识为某个组的一部分,则可以在其上添加系列ID。
{
"_id": <unique id>,
"field1" : "value1",
"_creation_timestamp" : <time when doc 1 was created>}
"family_id" : 0
},
{
"_id" : <unique id>,
"field1" : "value2",
"_creation_timestamp" : <time when doc 2 was created>
"family_id" : 0
}
要添加创建的时间戳,只需在插入时将include作为字段:
db.collection.insert({ "_id" : <unique id>, "field1" : "value3", "_creation_timestamp" : ISODate(), "family_id" : 0 })
如果确实保留了嵌入式结构,那么您也很可能不希望使用伪数组结构将文档作为值放置,其中键是索引。这将使搜索子文档的条件变得困难。改为使用数组:
{
"_id": <unique id>,
"embeddedDocs": [
{ "field1" : "value1", "_creation_timestamp" : <time when doc 1 was created> },
{ "field1" : "value2", "_creation_timestamp" : <time when doc 2 was created> }
]
}
要向此结构添加创建的时间戳,只需在推送到文档时包含时间戳:
db.collection.update({ "_id" : <unique id> }, { "$push" : { "embeddedDocs" : { "field1" : "value3", "_creation_timestamp" : ISODate() } } })