Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - Mongo push to array inside array

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'
                        }
                    ]
            }
        ]
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"}}}
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...