Robin Singh
Robin Singh

Reputation: 1796

How to filter data in array object using mongoDB?

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!

Upvotes: 0

Views: 421

Answers (1)

dhruv479
dhruv479

Reputation: 321

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,
      },
    ])

Upvotes: 1

Related Questions