2

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.

1 Answer 1

1
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

Sign up to request clarification or add additional context in comments.

5 Comments

But this would only work if the searchArray is the same everytime, i forgot to mention that the searchArray could be any hobby value
You can handle it in NodeJS, use forEach or map to build array for $or conditions. And pass it to the query. I will update description
I added another way, check it
Awesome thank you! the orArray approach was exactly what i was looking for!
I also added another way. I prefer the 2nd way, it's cleaner, lighter way. If your searchArray is array of string, you can pass it to $in immediate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.