Mongodb upsert嵌入式文档 [英] Mongodb upsert embedded document

查看:160
本文介绍了Mongodb upsert嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天每米有一份文件.如果他不存在,如何在数据数组中添加另一个子文档并创建整个文档?

I have a document per day per meter. How can I add another subdocument in the data array and create the whole document if he doesn't exists ?


{
  "key": "20120418_123456789",
  "data":[
     {
     "Meter": 123456789,
     "Dt": ISODate("2011-12-29T16:00:00.0Z"),
     "Energy": 25,
     "PMin": 11,
     "PMax": 16
     }
  ],
  "config": {"someparam": 4.5}
}

我可以为此使用upsert吗?

Can I use upsert for that purpose ?

结果将是文档是否存在:

The result will be if document exists :


{
  "key": "20120418_123456789",
  "data":[
     {
     "Meter": 123456789,
     "Dt": ISODate("2011-12-29T16:00:00.0Z"),
     "Energy": 25,
     "PMin": 11,
     "PMax": 16
     },
     {
     "Meter": 123456789,
     "Dt": ISODate("2011-12-29T16:15:00.0Z"),
     "Energy": 22,
     "PMin": 13,
     "PMax": 17
     }
  ],
  "config": {"someparam": 4.5}
}

预先感谢

推荐答案

我认为您想要的是$ addToSet命令-仅当元素不存在时才将其推入数组.为了简洁起见,我已简化了您的示例:

I think what you want is the $addToSet command - that will push an element to an array only if it does not already exist. I've simplified your example a bit for brevity:

db.meters.findOne()
{
    "_id" : ObjectId("4f8e95a718bc9c7da1e6511a"),
    "config" : {
        "someparam" : 4.5
    },
    "data" : [
        {
            "Meter" : 123456789,
        }
    ],
    "key" : "20120418_123456789"
}

现在运行:

db.meters.update({"key" : "20120418_123456789"}, {"$addToSet": {"data" : {"Meter" : 1234}}})

我们得到更新的版本:

db.meters.findOne()
{
    "_id" : ObjectId("4f8e95a718bc9c7da1e6511a"),
    "config" : {
        "someparam" : 4.5
    },
    "data" : [
        {
            "Meter" : 123456789,
        },
        {
            "Meter" : 1234
        }
    ],
    "key" : "20120418_123456789"
}

再次运行同一命令,结果不变.

Run the same command again and the result is unchanged.

注意:您可能会增加这些文档,特别是如果此字段不受限制并且通过这种方式进行更新而导致频繁(相对昂贵)的移动时,您应该在这里查找有关如何缓解此问题的想法:

Note: you are likely going to be growing these documents, especially if this field is unbounded and causing frequent (relatively expensive) moves by updating in this way - you should have a look here for ideas on how to mitigate this:

http://www.mongodb.org/display/DOCS/Padding+Factor#PaddingFactor -ManualPadding

这篇关于Mongodb upsert嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆