2

here's a simple aggregation that use to work and suddenly stopped, with the error

errmsg" : "insert for $out failed: { lastOp: { ts: Timestamp 1527170631000|78, t: 7 }, connectionId: 43852, err: \"E11000 duplicate key error collection: clients.tmp.agg_out.40 index: id dup key: { : ObjectId('5acdffd3957803129542e4b0') }\", code: 11000, codeName: \"DuplicateKey\", n: 0, ok: 1.0 }

db.collection.aggregate(
  {$match:{'events':{$elemMatch:{'field1':1,'field2':2}}}},
  {$unwind:'$events'},
  {$match:{'events.field1':1,'events.field2':2}},
  {$project:{'field3':'$events.field3'}},
  { $out : "results" }
 )

I am not comparing _id fields nor projecting any _id values. The collection 'results' is dropped before I run the aggregation, so it is empty. Where is the duplication???

Neil Lunn
  • 130,590
  • 33
  • 275
  • 280
  • 4
    The error is because `$unwind` copies the `_id` and in fact the whole document for every array entry and you did not remove the `_id` in the `$project`. `{ $project: { _id: 0, field3: '$event.field3' } }`. Not even clear why you are going to `$out` and probably could simply use a cursor. Mainly there's a better way of filtering the array content without using `$unwind`. See the [linked duplicate](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) for instruction on using `$filter`. – Neil Lunn May 24 '18 at 21:41
  • removing the _id field from $project as you suggested did the trick. thank you – Panikos Stavrou May 25 '18 at 07:22

0 Answers0