Home > Net >  Compare array within objects in an array of the same Mongo document
Compare array within objects in an array of the same Mongo document

Time:07-28

I have a Mongo database with multiple documents and they all contain 2 Items for in store and online locations. The difference will be that attributes within the items object may differ. I am trying to capture all documents that have differing attributes between the object items with the array.

I've tried using $expr and comparing the position of the elements such as "Items.0.Attributes" == "Items.1.Attributes" but had no luck.

{
        "ID" : "123456789",
        "Items" : [ 
            {
                "ItemDept" : "softLines",
                "ProductId" : {
                    "Name" : "shirts",
                    "_id" : "12345Shirts"
                },
                "Attributes" : [ "blue","small","mens"],
                "Season" : "Summer"
                "Location":"online"
            }
           , 
             {
                "ItemDept" : "softlines",
                "ProductId" : {
                    "Name" : "shirts",
                    "_id" : "12345Shirts")
                },
                "Attributes" : [ "blue","small","women"],
                "Season" : "Summer"
                "Location":"stores"
             }
            ]
          }

CodePudding user response:

If I understand what you want to find/output, here's one way you could do it.

db.collection.find({
  "$expr": {
    "$not": {
      "$setEquals": [
        {"$first": "$Items.Attributes"},
        {"$last": "$Items.Attributes"}
      ]
    }
  }
})

Try it on mongoplayground.net.

  • Related