Home > Enterprise >  Select and filter MongoDB subdocument array list
Select and filter MongoDB subdocument array list

Time:10-07

I am trying to select document with filter userInteractions array. I need to remove item where userdId = "633eb753c8e3d3fd71d1c254" and return document as result. It is easy way to approach it with MongoDB query?

https://mongoplayground.net/p/2UHw52QJkYu

Example of JSON document:

{
  "_id": {
    "$oid": "633c25965034208db76cfb1e"
  },
  "email": "[email protected]",
  "users": [
    {
      "type": "person",   
      "isActive": true,
      "userInteractions": [
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c254"
          },
          "firstName": "Tom",
          "lastName": "Hawkins",
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c222"
          },
          "firstName": "Melan",
          "lastName": "Key",
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c259"
          },
          "firstName": "Ken",
          "lastName": "Olibar",
        },
      ]
    }
  ]
}

Expecting output:

{
  "_id": {
    "$oid": "633c25965034208db76cfb1e"
  },
  "email": "[email protected]",
  "users": [
    {
      "type": "person",   
      "isActive": true,
      "userInteractions": [
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c222"
          },
          "firstName": "Melan",
          "lastName": "Key",
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c259"
          },
          "firstName": "Ken",
          "lastName": "Olibar",
        },
      ]
    }
  ]
}

CodePudding user response:

  1. $set - Set users field.

    1.1. $map - Iterate the users array and return a new array.

    1.1.1. $mergeObjects - Merge the current iterated document and the document from the result 1.1.1.1.

    1.1.1.1. $filter - Filter the document(s) from the userInteractions array from the current iterated document.

db.collection.aggregate([
  {
    $set: {
      users: {
        $map: {
          input: "$users",
          as: "user",
          in: {
            $mergeObjects: [
              "$$user",
              {
                userInteractions: {
                  $filter: {
                    input: "$$user.userInteractions",
                    cond: {
                      $ne: [
                        "$$this.userId",
                        {
                          $toObjectId: "633eb753c8e3d3fd71d1c254"
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

  • Related