0

I have a MongoDb document with the following format

{
  "_id": { "$oid": "587b5a985390100541f52d8e" },
  "name": "M&G",
  "type": "F",
  "category": "Multi",
  "data": [
      {
        "date": { "$date": "2014-08-03T22:00:00.000Z" },
        "value": 13.172
      },
      {
        "date": { "$date": "2014-08-04T22:00:00.000Z" },
        "value": 13.133
      }
  ],
  "meta": {
    "code": "103039925"
  }
}

I use

 var cname =  // collection name
 var docs= [] // array of objecs e.g. {date:<Date> value:<Number> }
 var opts = { w: 1, upsert: false, returnOriginal: false };

 connection.collection(cname)
 .findOneAndUpdate(query, { $addToSet: {data: { $each: docs }} }, opts, function (err, res) {
  // do something 
 });

my problem is $addToSet ensure no duplicate object is added to the set but use object equality

this object has duplicate date but is not recognized as a duplicate by $addToSet

{
    "date": { "$date": "2014-08-04T22:00:00.000Z" },
    "value": 0
}

my application requires that any object in the array has unique date. Is there a way to obtain that? actually if an object with duplicate date is observed it should update the value of the object

Gavello
  • 1,399
  • 2
  • 13
  • 25

1 Answers1

0

In your case you are using $addToSet with $each which perform on Array as per my knowledge but in your case you are using Object array which is the form of Embedded Document in MongoDB.

I think you can use this approach or may other approach are there

{
  "_id": { "$oid": "587b5a985390100541f52d8e" },
  "name": "M&G",
  "type": "F",
  "category": "Multi",
  "data": [
      {
        "date": "2014-08-03T22:00:00.000Z" ,
        "value": 13.172
      },
      {
        "date": "2014-08-04T22:00:00.000Z" ,
        "value": 13.133
      }
  ],
  "meta": {
    "code": "103039925"
  }
}


 var cname =  // collection name
 var docs= [] // array of objecs e.g. {date:<Date> value:<Number> }
 var opts = { w: 1, upsert: false, returnOriginal: false };

 connection.collection(cname)
 .update({'data.date': { '$ne': new Date() } },{ $push: {data: docs } }, opts, function (err, res) {
  // do something 
 });

you can also check from here

Community
  • 1
  • 1
Manjeet Thakur
  • 2,288
  • 1
  • 16
  • 35
  • I do not think your suggestion is going to work... { $push: {data: docs } } i think should be { $push: { data: { $each: docs } } } but I can not get the {'data.date': { '$ne': new Date() } } part. my target is to append the new object to the data array only if it does not has an object with the same date. – Gavello Jan 24 '17 at 20:01