0

I have a query that is running fine, now i have requirement to filter some data that is inside array. I don't know how to do that. Below is my code. Please guide me where i am wrong.

Request data

[
  'Online Casino/Betting',
  'Other ',
  'Prefer not to say ',
  'Do you really care ? :) ',
  'Spend time with friends'
]

Database Data

"interests" : [
        {
            "name" : "Computers/internet", 
            "_id" : ObjectId("60752406d8e7213e6b5306de"), 
            "id" : NumberInt(1)
        }, 
        {
            "name" : "Astrology/Spiritualism", 
            "_id" : ObjectId("60752406d8e7213e6b5306df"), 
            "id" : NumberInt(3)
        }, 
        {
            "name" : "Cars & motorbikes", 
            "_id" : ObjectId("60752406d8e7213e6b5306e0"), 
            "id" : NumberInt(2)
        }
    ], 

Query

if (filterData.interests != undefined && filterData.interests.length > 0) {
  interests = {
    interests: { $elemMatch: { $and: [{ name: filterData.interests }] } }
  }
}

  User.aggregate([
      coordinatesCondition,
      {
        $match: {
          $and: [
            exerciseHabitsCondition,
            interests
          ],
        },
      },
      {
        $sort: lastActivity,
      },
      { $limit: skip + 12 },
      { $skip: skip },
      {
        $lookup: {
          from: "favorites",
          localField: "_id",
          foreignField: "favorites.favoriteUserId",
          as: "favUsers",
        },
      },
    ])

Any solution appreciated!

4
  • To filter elements from an array in an aggregation use $filter array operator. Commented Apr 27, 2021 at 9:47
  • @prasad_ can you please elaborate. Actually i am passing data in array format. Commented Apr 27, 2021 at 9:49
  • I have array of names Commented Apr 27, 2021 at 9:50
  • @robin can you provide the exact mongoDB query being executed in the debug mode with minimal stages in aggregation. Commented Apr 27, 2021 at 13:50

1 Answer 1

1

as per my understanding you want to match the result with interests in the req data. I am sharing a simple update, that can work well for you.

if (filterData.interests != undefined && filterData.interests.length > 0) {
  interestsQuery = {
    'interests.name': { $in: filterData.interests } }
  }
}

User.aggregate([
      coordinatesCondition,
      {
        $match: {
          $and: [
            exerciseHabitsCondition,
            interestsQuery
          ],
        },
      },
      {
        $sort: lastActivity,
      },
    ])
Sign up to request clarification or add additional context in comments.

Comments

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.