Home > Blockchain >  Mongoose Aggregate match if an Array contains any value of another Array
Mongoose Aggregate match if an Array contains any value of another Array

Time:10-27

I am trying to match by comparing the values inside the values of another array, and return it if any one of the values in the 1st array match any one value of the 2nd array. I have a user profile like this

{
"user": "bob"
"hobbies": [jogging]
 },
{
"user": "bill"
"hobbies": [reading, drawing]
 },
{
"user": "thomas"
"hobbies": [reading, cooking]
 }
{
"user": "susan"
"hobbies": [coding, piano]
 }

My mongoose search query as an example is this array [coding, reading] (but could include any hobby value) and i would like to have this as an output:

 {
"user": "bill"
"hobbies": [reading, drawing]
 },
{
"user": "thomas"
"hobbies": [reading, cooking]
 }
{
"user": "susan"
"hobbies": [coding, piano]
 }

I tried:

{"$match": {"$expr": {"$in": [searchArray.toString(), "$hobbies"]}}}

but this only works aslong as the search array has only one value in it.

CodePudding user response:

const searchArray = ["reading", "coding"];

const orArray = searchArray.map((seachValue) => {
  return {
    hobies: searchValue,
  }
});

collection.aggregate([{
  $match: { $or: orArray }
}])

The query:

db.collection.aggregate([
  {
    $match: {
      "$or": [
        {
          hobbies: "reading"
        },
        {
          hobbies: "coding"
        }
      ]
    }
  }
])

Or you can use another way, no need to handle arr:


db.collection.aggregate([
  {
    $match: {
      hobbies: {
        $in: [
          "reading",
          "coding"
        ]
      }
    }
  }
])

Run here

  • Related