0

I need to run my cron scripts to update/insert (upsert) threads (emails) for each user. I have collection that is structured such as:

{ 
    "id" : ObjectId("57d7fc5fd34228c47059"), 
    "id" : "userid", 
    "primaryEmail" : "user@mail.com", 
    "threads_list" : [

    ]
},
{ 
    "_id" : ObjectId("57d7346a73d128c47059"), 
    "id" : "uderid", 
    "primaryEmail" : "user2@mail.com", 
    "threads_list" : [

    ]
}
...

I want to store threads into threads_list. But I also want to update them if they already exist or just skip it if it hasn't change since last upsert, just like I would create collection for each user and update emails stored inside with updateOne method that has {upsert:true} param.

I don't mind changing threads_list attribute into object type if necessary.

How is that done properly?

Kunok
  • 8,089
  • 8
  • 48
  • 89

1 Answers1

1

Try this code

db.collection('users').update(
          { _id:user.id, 
            $set: {'primaryEmail': newEmail} 
          },
          { $addToSet: { 'threads_list': { $each: resp.labels } } }
        );
vdj4y
  • 2,649
  • 2
  • 21
  • 31
  • Yes it was typo. And yes I want to push thread objects that I fetched from API into array `threads_list`. In case that email already exists, update it rather than inserting duplicates. – Kunok Sep 13 '16 at 14:25