简体   繁体   中英

Adding/Updating object to/in nested array in mongodb

I have a document:

{
  "_id": "57d421bbbc44538f0634081c",
  "in_date": "1473724800",
  "bboxes": [
      { "bbox_index": "4124432432311", "data": {} },
      { "bbox_index": "4124435342332", "data": {} },
      ...
  ]
}

I'm trying to update entire object found in bboxes with specific bboxes.bbox_index :

bbox_index = 4124432432311
in_date = 1473724800

self.db['my_table'].update(
    {
        'in_date': in_date,
        'bboxes.bbox_index': bbox_index
    }, 
    {
        '$set': {'bboxes.$': dict(item)}
    },
    upsert=True
)

I expect this object { "bbox_index": "4124432432311", "data": {} } to be replaced with dict(item)

This works fine when object with required bbox_index already exists. When it doesn't exist, I get The positional operator did not find the match needed from the query. Unexpanded update: bboxes.$ The positional operator did not find the match needed from the query. Unexpanded update: bboxes.$

In order to make it work I have to do the same query but instead of $set do {'$push': {'bboxes': dict(item)}} . Of course, this doesn't work well when I do already have required object in database. In this case I'm pushing same object again. Possible solution would be to check for the object before updating it but I wanted to make it in one single expression. I thought upsert=True was made exactly for this purpose. Is there any way to do what I want?

Instead of using $push , you can use $addToSet which will insert a new entry in the array only if the entry doesn't exist yet.

To paraphrase the relevant manual page https://docs.mongodb.com/manual/reference/operator/update/addToSet/ :

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM