0

I have a document structure like the following:

{
    "_id" : ObjectId("58be819769f922b8427e7f10"),
    "id" : "58be7a4cfc13ae51020002cc",
    "source" : "facebook",
    "source_id" : "b37f5e43-ea3f-46d2-b2b0-b8f55e923933",
    "data" : [
        {
            "date" : "5/8/2016",
            "topics" : [
                "Vectorworks",
                "Statistics",
                "Flight Planning",
                "HTK",
                "Custom Furniture"
            ]
        },
        {
            "date" : "7/22/2016",
            "topics" : [
                "FDR",
                "NS2",
                "Power Plants"
            ]
        },
        {
            "date" : "12/23/2016",
            "topics" : [
                "LTV",
                "MMS"
            ]
        }
    ]
}

Now, If I want to append more topics to the date "12/23/2016", I can do that using:

db.revision.findOneAndUpdate({id: '58be7a4cfc13ae51020002cc', data: {$elemMatch: {date: '03/17/2017'}}}, {$push: {'data.$.topics': 'java lambda'}},{upsert: true})

But, how can I add a new object, to data array when the entry for a date is not present?

Rajat Saxena
  • 3,834
  • 5
  • 45
  • 63
  • I'm just getting started with mongodb but this looks like it: https://docs.mongodb.com/manual/reference/operator/update/addToSet/#up._S_addToSet – jeffery_the_wind Mar 18 '17 at 09:02
  • Also here looks like it: http://stackoverflow.com/questions/13987365/how-to-insert-an-element-to-mongodb-internal-list – jeffery_the_wind Mar 18 '17 at 09:07
  • 1
    @jeffery_the_wind Thank you, $addToSet helped me in dealing with duplicate entries. But how can I add something like `{ date: "03/18/2017", topics: ['js']}` when such an entry does not exist and the `find` clause fails? – Rajat Saxena Mar 18 '17 at 09:16

1 Answers1

2

First insert an empty data doc for the required date field, if its not already present

db.revision.update( {id: '58be7a4cfc13ae51020002cc', "data.date" : {$ne : '03/17/2017' }} , 
                {$addToSet : {"data" : {'date' : '03/17/2017'}} } ,
                false ,  //<-- upsert
                true ); //<-- multi

Then update the same using the update query as devised by you

db.revision.findOneAndUpdate({id: '58be7a4cfc13ae51020002cc', data: {$elemMatch: {date: '03/17/2017'}}}, {$push: {'data.$.topics': 'java lambda'}},{upsert: true})
Rahul
  • 15,979
  • 4
  • 42
  • 63
  • It seems like a good solution. Can you please tell me what do the last two parameter in update() method signify? I went to Mongodb's `update()` documentation but it seems to be `update(query, update, options)`. – Rajat Saxena Mar 18 '17 at 10:28
  • 1st upsert, 2nd multi. Updated the answer – Rahul Mar 18 '17 at 10:55
  • @RajatSaxena if it solved your concern, can you please accept this answer. – Rahul Mar 27 '17 at 04:15