Kunok Kunok - 2 months ago 7
Javascript Question

How to store large amount of messages for users in MongoDB?

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?

Answer

Try this code

db.collection('users').update(
          { _id:user.id, 
            $set: {'primaryEmail': newEmail} 
          },
          { $addToSet: { 'threads_list': { $each: resp.labels } } }
        );