Home > database >  MongoDB update if value from one array is in other array
MongoDB update if value from one array is in other array

Time:12-16

I have a collection (1) with the following field:

{
 _id: 1,
 value: ["A","B","C","D"]
}

and inside another collection (2), I have the following fields:

{
 _id: 1,
 predicted_value: [
  {
   value: "A",
   num: 1,
  },
  {
   value: "B",
   num: 2,
  },       
  {
   value: "D",
   num: 2
  }
 ],
 real_prediction: <Collection1.value>
 predicted_by: "Person1",
 is_correct_prediction: <bool>
}

My goal is now to update the second collection by the following: If an entry gets put into value of collection 1 (I already am listening to this type of event), collection 2 should update the real prediction by gathering the values of collection 1 and update the boolean is_correct_prediction, if one element in the value array is also in the predicted_value array. In this case it should be set to True, by default it is False. Is there some sort of mongo query, that can manage this? It can definetly be done with Python, but is it possible to also use mongo only?

CodePudding user response:

You can perform a $lookup to collection 1 and use $setIntersection to check whether is_correct_prediction should be true.

db.coll2.aggregate([
  {
    "$lookup": {
      "from": "coll1",
      "localField": "_id",
      "foreignField": "_id",
      "as": "coll1Lookup"
    }
  },
  {
    "$unwind": "$coll1Lookup"
  },
  {
    $set: {
      real_prediction: "$coll1Lookup.value",
      is_correct_prediction: {
        $ne: [
          [],
          {
            "$setIntersection": [
              "$coll1Lookup.value",
              "$predicted_value.value"
            ]
          }
        ]
      }
    }
  },
  {
    $unset: "coll1Lookup"
  },
  {
    "$merge": {
      "into": "coll2",
      "on": "_id"
    }
  }
])

Mongo Playground

  • Related