2014년 12월 24일 수요일

Check for array element in Cursor data set

I am stuck up with the following problem, I have array of Items and Amount associated with it. I want to fetch the records depending on the amount and check for Item, if the item is present then increment the count. I am using Pymongo.

"_id" : ObjectId("549aaa660d9f0402c79f8f02"),
    
    "Items" : [
        {
            "count" : 2,
            "name" : "Item1"
        },
        {
            "count" : 1,
            "name" : "Item2"
        },
        {
            "count" : 1,
            "name" : "Item3"
        },
        {
            "count" : 1,
            "name" : "Item4"
        }
    ],
    "Amount" : 420
}
"_id" : ObjectId("549a9a550d9f047f1408c12c"),
    
    "Items" : [
        
        {
            "count" : 1,
            "name" : "Item3"
        },
        {
            "count" : 1,
            "name" : "Item4"
        }
    ],
    "Amount" : 150
}
item = item3
cursor = fastqseq.find({"amount":420},{"_id":1,"Amount":1,"Items":1})

for d in cursor
    if(item in d["Items"]['$']["name"])):
        then update the count


d["Items"]['$']["name"]) is giving me an error. How the find whether given item is present in 'Items' array elements



Why not just filter out the documents you want in the query?

In fact, wouldn't the following update do exactly what you are trying to do in a single instruction?

db.collection.update( { "Amount":420, "Items.name":"Item3"}, {$inc:{"Items.$.count":1}}, {multi:true})

This says match all documents where Amount is 420 and Items array has element with name "Item3" and then in each of those documents increment by one the count in the same array element that matched "name=Item3".



My mistake, I did not give the whole query, sorry for that. You are right with the query.

I want to find whether the Item is there in the Items list. is there any wild character like  $ for indices 

for d in cursor
    if(Amount==420 and item in d["Items"]['$']["name"])):
        then update the count
     if (Amount==420 and Item3 is not present)
           then update the record ($set name:item and count:1)
    else
        Insert the whole record. 




You can update the count atomically using the update statement that I showed - that only works if the item is there.

If the item is not there, then you want to push a new element to the array - unfortunately that can't be done in a single operation with the above (there are a number of enhancement requests in Jira discussing inability to atomically "push-upsert" a new array element that doesn't exist.

To create a new entire document you can just use the upsert option to the update, but again, it's tricky to combine that with the update that you want to do.


댓글 없음:

댓글 쓰기