Home > Mobile >  $in Query on Array Field Mongo db
$in Query on Array Field Mongo db

Time:10-12

I have a doc like this

{
  "_id" : "oidfi",
   "users": [
        {
            "_id": "q",
            "tags": ["a", "b", "c"],
            "age": 20

        },
        {
            "_id": "q",
            "tags": ["x", "y", "z"],
            "age": 30

        }
    ],
    "type": "repo"
}

I want to filter the users array with several fields ( I'm able to do that with the below query )

    {
        "$match": {
            "$and": [
                {
                    "_id": "a506f8af6f510f616bea14715276d474d2b363f0aef10443cc0f11559b139147"
                }
            ]
        }
    },
    {
        "$project": {
            "users": {
                "$filter": {
                    "input": "$users",
                    "as": "users",
                    "cond": {
                        "$and": [
                            {
                                "$gte": [
                                    "$$user.age",
                                    15
                                ]
                            }
                        ]
                    }
                }
            }
        }
    }
]

is there a way for me to add condition where I give a list of tags items and get the users who are matching at least one item from their tags array

$$user.tags.containsAny(["a", "x"])

Thanks

CodePudding user response:

You can do the followings in an aggregation pipeline:

  1. $setIntersection to find out the intersection of the users.tags array and your input array i.e. ["a", "x"] in your example
  2. $size to find the size of array in step 1
  3. $match by the size of step 2 larger than 0
"anyTagsMatched": {
        $gt: [
          {
            $size: {
              "$setIntersection": [
                "$users.tags",
                [
                  "a",
                  "x"
                ]
              ]
            }
          },
          0
        ]
      }

Here is the Mongo playground for your reference.

CodePudding user response:

You may have like following

db.collection.aggregate([
  {
    "$project": {
      "users": {
        "$filter": {
          "input": "$users",
          "cond": {
            "$and": [
              { "$gte": [ "$$this.age", 15 ] },
              {
                $gt: [
                  {
                    $size: {
                      "$setIntersection": [
                        "$$this.tags",
                        [ "a", "x" ]
                      ]
                    }
                  },
                  0
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Working Mongo playground

  • Related