Mongo推送到数组内部的数组 [英] Mongo push to array inside array

查看:76
本文介绍了Mongo推送到数组内部的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im与mongo兼容,到目前为止,使用它没有问题.直到我坚持这一点.我需要将文档推入数组中的数组.可以参考下面的json.

im new with mongo and so far have no issue using it. Until i stuck at this. I need to push a document to an array inside an array. Can refer to json below.

{
    'user_id':'{1231mjnD-32JIjn-3213}',
    'name':'John',
    'campaigns':
        [
            {
                'campaign_id':3221,
                'start_date':'12-01-2012',
                'messages':
                    [
                        {
                            'message_id':211134,
                            'email':'john@gmail.com'
                        }
                    ]
            },
            {
                'campaign_id':3222,
                'start_date':'13-01-2012',
                'messages':
                    [
                        {
                            'message_id':315521,
                            'email':'john@gmail.com'
                        }
                    ]
            }
        ]
}

我想将一个文档推送到Campaigns数组中的消息数组中(无论顺序如何).这意味着,我需要将新文档附加到消息数组中.所有这些消息均来自另一个阵列或每个用户的广告系列.我正在使用python,所以我的代码将是这样.

I want to push one document to an array of messages in a campaigns array(regardless ordering). Meaning that, i need to append new document to an array of messages. And all those messages is from inside another array or campaigns per user. Im using python so my code will be like this.

query = {"user_id" : "{1231mjnD-32JIjn-3213}", "campaigns.campaign_id": 3221}
message = {"message_id":4213122, "email":"john@gmail.com"}
op = {"$push" : {"campaigns.messages":message}}
mongo.TestDatabase.members.update(query, op)

执行时没有错误.但是该文档似乎没有任何更改(未进行任何更新).我在这里做错什么了?

There is no error upon execution. But the document seems to have no changes(no update made). What am i doing wrong here?

推荐答案

在数组内部包含数组几乎总是一个坏主意,原因有很多.我将这些广告系列放入一个专用集合中,以便它们成为顶级文档.

Having arrays inside arrays is almost always a bad idea for a number of reasons. I'd put the campaigns in a dedicated collection so they become top level documents.

也就是说,您可以通过以下方式推送到特定广告系列的消息数组:

That said, you can push to a message array of a specific campaign through :

db.members.update(
    {"user_id" : "{1231mjnD-32JIjn-3213}", "campaigns.campaign_id": 3221},
    {$push:{"campaigns.$.messages":{"message_id":4213122, "email":"john@gmail.com"}}}
)

这篇关于Mongo推送到数组内部的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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