0

I have several JSON like the one below and I need to chek all of them that have the properties "name" and "skd" duplicates as shown.

{
    "_id" : ObjectId("65498654654"),
    "name": "Orden",
    "__v" : 0,
    "inventory" : [ 
        {
            "name" : "firstElement",
            "skd" : "9879",            
            "name" : "AnotherfirstElement1",
            "skd" : "32197",
        }, 
        {
            "name" : "secondElement",
            "skd" : "321654",            
        }, 
        {
            "name" : "thirdElement",
            "skd" : "321654"            
        }
   ]
}

I tried this but not working

db.mycollection.aggregate([
  
  { $unwind: "$inventory" },
  {
    $group: {
      _id: {
        _id: "$_id",
        names: "$inventory.name"
      },
      sum: { $sum: 1 }
    }
  },
  { $match: { sum: { $gt: 1 } } }
])

I expect something to show me that position 0 has the duplicate properties.

1 Answers1

0

This is a good rundown on duplicate keys in JSON: Does JSON syntax allow duplicate keys in an object?

The Node.js driver for MongoDB will not respect duplicate keys when serializing to BSON. Only one of the keys will be chosen, and I'm not sure if this is deterministic, it's an undocumented implementation detail.

Regardless, it is not recommended to work with objects that have duplicate keys even though it might technically be possible to do so.

MongoDB does not make specific guarantees on querying objects with duplicate keys. It's essentially undefined behavior.

Matt Kneiser
  • 1,982
  • 18
  • 23