更新 MongoDB 中的嵌套文档 [英] Updating nested document in MongoDB

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

问题描述

我正在尝试更新嵌套在 MongDB 文档中的哈希.我知道用于数组的 $push 函数和用于完全覆盖元素的 $set ,但我无法完全得到我正在寻找的行为.

I'm trying to update a hash that's nested in a MongDB document. I know about the $push function for arrays, and $set for completely overwriting elements, but I can't quite get the behaviour I'm looking for.

这是我想要得到的:

之前:

{
  'id' => 1234,
  'evaluators' => {
    'A' => { 'x' => 2, 'y' => 4 },
  }
}

预期,之后:

{
  'id' => 1234,
  'evaluators' => {
    'A' => { 'x' => 2, 'y' => 4 },
    'B' => { 'x' => 3, 'y' => 5 },
  }
}

我尝试过(在 Ruby 中):

I've tried doing (in Ruby):

coll.update({ :id => id },
            { '$set' => {
                'evaluators' => {
                    evaluator_name => { 'adequacy' => adequacy, 
                                        'fluency'  => fluency }
                }
            } } )

但它覆盖了我的 evaluators 哈希的内容,我最终得到:

But it overwrites the contents of my evaluators hash and I end up with:

{
  'id' => 1234,
  'evaluators' => {
    'B' => { 'x' => 3, 'y' => 5 },
  }
}

我可以执行查询以将整个文档加载到 Ruby 中,更改数据并将其重新插入数据库,但我想知道是否有我不知道的更好方法.

I could do a query to load the entire document into Ruby, change the data and re-insert it to the DB but I was wondering if there was a better way that I don't know about.

推荐答案

试试这个:

coll.update({ :id = > id }, { '$set' => {
    "evaluators.#{evaluator_name}" => {
        'adequacy' => adequacy, 'fluency' => fluency
    }
}})

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

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