how to catch mongo change streams when one array changes within an object

43 Views Asked by At

I am trying to setup a change stream filter to detect only when a particular document (_id) has a change within a particular array of key/values. I have the following example mongodb doc, i am trying to detect a change within the 'inventory.0.APPLE' array. note that there is also a duplicate array in the 'inventory.0.DiscountBin.APPLE' which i am not interested in. I've tried the below without any luck.

{
    "_id": {
        "$oid": "64d43991678e200790d54c01"
    },
    "GroceryPlatform": "FruitBasket",
    "StoreName": "Fruit Kingdom",
    "groceryType": "Assorted",
    "storeID": "64d43991678e200790d54c01",
    "inventory": [{
        "Discounts": "Online",
        "Info1": {
            "Layout": "Honeycomb",
            "Lighting": "Grid",
            "Fitout": "Modern Black",
            "Version": "12.2.0"
        },
        "Info3": {
            "Eftpos": {
                "$numberInt": "51"
            },
            "Version": "45.1.11"
        },
        "EnergySaver": "ON",
        "NetworkInfo2": {
            "Hostname": "FruitBasket-010100",
            "IPAddress": "10.10.20.227"
        },
        "APPLE": {
            "Quality": {
                "$numberDouble": "70.868"
            },
            "Weight": {
                "$numberDouble": "0.291"
            },
            "Color": {
                "$numberDouble": "0.78"
            },
            "UsedBy": {
                "$numberDouble": "4.59"
            }
        },
        "Time": "2023-08-20T08:50:27",
        "TotalStock": {
            "$numberInt": "24"
        },
        "AverageCost": {
            "$numberInt": "19"
        },
        "WASTE": {
            "PowerDelta": {
                "$numberInt": "45"
            }
        },
        "DiscountBin": {
            "APPLE": {
                "Quality": {
                    "$numberDouble": "70.868"
                },
                "Weight": {
                    "$numberDouble": "0.291"
                },
                "Color": {
                    "$numberDouble": "0.78"
                },
                "UsedBy": {
                    "$numberDouble": "4.59"
                }
            },
            "Time": "2023-08-20T08:43:39"
        }
    }],
    "__v": {
        "$numberInt": "0"
    }
}

  {
    $match: {
      $and: [
        { 'fullDocument._id': new mongoose.Types.ObjectId(documentId) },
        { 'updateDescription.updatedFields': { $exists: true } },
        { 'updateDescription.updatedFields.inventory.0.APPLE': { $exists: true } }
      ]
    }
  }
]);
0

There are 0 best solutions below