$push 嵌入文档数组中 [英] $push in embedded document array

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

问题描述

我想将所有消息标记为jim"已读.这是一个线程的结构:

I would like to mark all messages as read by 'jim'. Here is the structure of a thread:

db.threads.save({
    messages: [
        {
            read_by: ['bob', 'jim']
        },
        {
            read_by: ['bob']
        },
        {
            read_by: ['bob']
        }
    ]
})

如您所见,'jim' 已经阅读了一条消息,其余的仅由 'bob' 阅读.我想查找并修改任何嵌入的文档,以便将jim"附加到 read_by 数组.

As you can see, one message has already been read by 'jim', the rest only by 'bob'. I'd like to find and modify any embedded documents so that 'jim' is appended to the read_by array.

这是我得到的:

db.threads.findAndModify({
    query: {
        'messages.read_by': {
            $ne: 'jim'
        }
    },
    update: {
        $push: {
            'messages.$.read_by': 'jim'
        }
    }
})

我收到此错误:

未捕获的异常:findAndModifyFailed 失败:无法使用字符串字段名称 [$] 附加到数组"

uncaught exception: findAndModifyFailed failed: "can't append to array using string field name [$]"

查询与 db.threads.find() 一起使用,所以我猜问题出在 findAndModify() 调用的更新部分.

The query works with a db.threads.find() so I guess the problem is with the update part of the findAndModify() call.

推荐答案

我知道它已经有一段时间了,但推入嵌套文档确实是可能的.您需要在其中添加一个 each .例如,

I know its been a while, but pushes into nested documents is indeed possible. You need to add an each into it. For example,

db.threads.update({
    'messages.read_by': {
        $ne: 'jim'
    }
},
{
    $push: {
        'messages.read_by': {
            $each: ['jim']
        }
    }
}
)

查看更多示例 - http://docs.mongodb.org/manual/reference/operator/update/push/

即使您只传递一个值,对于嵌套数组,您也需要传递 $each.如果文档已经包含一个 read_by 字段,其中有一些值,那么没有 each 的更新会起作用.无论该字段是否存在,使用 $each 都将起作用.

Even though you are just passing only one value, for nested arrays, you need to pass $each. If the document already contains a read_by field with some values in it, then an update without the each works. Using the $each will work irrespective of whether the field exists or not.

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

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