我有一个具有以下结构的 mongo 集合:
{
"_id" : ObjectId("..."),
history : {
}
}
现在我必须更新此类集合,将其推送到 history
子文档新的关联对象中,因此它应该如下所示:
{
"_id" : ObjectId("..."),
history : {
"06/04/2015" : {}
}
}
这样做的正确方法是什么?
最佳答案
鉴于数据格式:
> db.test.insert({_id: oid, history: {} })
在嵌入文档历史记录
中添加新字段非常容易。您只需要 $set
更新运算符,您将不得不使用 dot-notation指定字段:
> db.test.update({_id:oid},{$set: { "history.06/04/2015": "6 of june"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
制作:
> db.test.find({_id:oid},{_id:0})
{ "history" : { "06/04/2015" : "6 of june" } }
请注意$set
操作是idempotent :
> db.test.update({_id:oid},{$set: { "history.06/04/2015": "6 of june"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.test.find({_id:oid},{_id:0})
{ "history" : { "06/04/2015" : "6 of june" } }
话虽这么说,正如评论中所解释的,这可能不是存储历史记录的最佳方式。顺便提一下,例如,它会阻止按日期正确索引您的历史记录。
事实上,有许多不同的方式来存储历史数据。只是几个例子。所有这些都有(可能)优点和(绝对)缺点:
{
history: [
{ "06/04/2015": "6 of June" },
]
}
{
history: {
"2015" : [
{ "06/04": "6 of June" },
]
}
}
{
history: {
{
year: "2015";
data: [
{ "06/04": "6 of June" },
]
}
}
}
等等
顺便说一句,使用正确的日期对象可能比使用字符串来存储日期更好。我稍后在这里使用它只是为了避免使示例变得更加麻烦。
关于json - 将新的关键元素推送到 mongodb 的子文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30651063/