R2D2
R2D2

Reputation: 10737

get elements from nested array not existing in another nested array

Please, help! I need to get list of elements in nested array that do not exist in another nested array, example document:

{
"_id": 123,
_a: [
  {
    aid: 10,
    _p: [
      {
        pid: 1,
        x: "C"
      },
      {
        pid: 2,
        x: "B"
      },
      {
        pid: 4,
        x: "A"
      }
    ],
    _d: [
      {
        pid: 2,
        x: "M"
      },
      {
        pid: 5,
        x: "M"
      },
      {
        pid: 7,
        x: "M"
      }
    ]
  }
 ]
}

Expected output:

   { aid:10 , pid:5}
   { aid:10 , pid:7} 

Task1: I need to find all the _a[]._d[].pid that do not exist in _a[]._p[]

Task2: I need to remove all objects from _a[]._d[] with pid that do not exist in _a[]._p[]

playground

Upvotes: 0

Views: 44

Answers (1)

YuTing
YuTing

Reputation: 6629

Use $setDifference

db.collection.aggregate([
  {
    $unwind: "$_a"
  },
  {
    $project: {
      aid: "$_a.aid",
      pid: {
        $setDifference: [
          "$_a._d",
          "$_a._p"
        ]
      }
    }
  },
  {
    $unwind: "$pid"
  },
  {
    $project: {
      aid: 1,
      pid: "$pid.pid"
    }
  }
])

mongoplayground

Upvotes: 1

Related Questions