gpt4 book ai didi

json - 将新的关键元素推送到 mongodb 的子文档中

转载 作者:可可西里 更新时间:2023-11-01 09:59:04 26 4
gpt4 key购买 nike

我有一个具有以下结构的 mongo 集合:

{
"_id" : ObjectId("..."),
history : {

}
}

现在我必须更新推送到 history 子文档新关联对象中的此类集合,因此它应该如下所示:

{
"_id" : ObjectId("..."),
history : {
"06/04/2015" : {}
}
}

这样做的正确方法是什么?

最佳答案

给定数据格式:

> db.test.insert({_id: oid, history: {} })

在嵌入文档 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com