Update a few fields in nested array in mongodb (with pymongo)

464 views Asked by At

I am trying to update a few fields within an array within array

An example document is like this:

{
id: 987654321
tweets: [
    {
        text: "RT @947FreshFM: A vigil will be held for #SandyHook victims at UMd. at 7pm at Nyumburu Ampitheater. @BlackTerp",
        urls: [

        ],
        id: 279718351289348100
    },
    {
        text: "RT @WTOP: McDonnell: If you talk completely about guns, I think you're missing the point. #AskTheGov http://t.co/hbFt7t1n",
        urls: [
            {
                status: null,
                domain: null,
                url: "http://t.co/hbFt7t1n",
                period: null,
                resolved_url: null,
                annotation: null
            }
        ],
        id: 281061376275906560
    }
],

}

I want to update the urls array as:

        urls: [
            {
                status: null,
                domain: "wtop.com",
                url: "http://t.co/hbFt7t1n",
                period: null,
                resolved_url: "http://wtop.com/?nid=610&sid=3162096",
                annotation: null,
                annotation2: "guncontrol"
            }
        ],

I am using something like this to do the updating:

collection.update({"id":987654321, "tweets.id":281061376275906560,"tweets.urls.url":"http://t.co/hbFt7t1n"},
{"$set":{
    "tweets.urls.resolved_url":"http://wtop.com/?nid=610&sid=3162096",
    "tweets.urls.domain": "wtop.com",
    "tweets.urls.annotation2":"guncontrol"
}}, False,False)

However it gives me error

can't append to array using string field name [urls]

Any suggestions?

1

There are 1 answers

0
mikeba On

I can't be certain, but this might be what's going on. From your example document, your model has this schema:

{  
    id: Number,  
    tweets: Array  
}

When you search for the instance of the model in

collection.update( {
    "id": 987654321,
    "tweets.id": 281061376275906560,
    "tweets.urls.url": "http://t.co/hbFt7t1n"
}, ...)`

It's likely that it's not finding the instance of the model you're looking for.

I would try running this script to see if your search criteria are valid:

console.log(collection.find({
    "id": 987654321,
    "tweets.id": 281061376275906560,
    "tweets.urls.url": "http://t.co/hbFt7t1n"
}));

Hope it helps!