Praveen Lohar
Praveen Lohar

Reputation: 17

How get to All values matching the query from mongodoDb at Once from multiple documents having nested array of objects

My user Model in mongoDb has following Data. What i wanted is for a user with document id ==(60202754626aea0f30473f09) i wanted to get all object from cardsArray and loginIdsArray whose isFavourite value == true

I did Applied this code but at console.log(ans) is empty array [ ]. Also this code is for loginidsArray.How can i get all values from both array at once

  const ans = await UserDatabase.aggregate([
      { $match: { _id: req.query.user_id } },
      {
        $project: {
          loginIdsArray: {
            $filter: {
              input: "$loginIdsArray",
              as: "item",
              cond: { $eq: ["$$item.isFavourite", true] },
            },
          },
        },
      },
    ]);
    // console.log("fetched fav", response);
    console.log("ans", ans);

{
  "_id": "60202754626aea0f30473f09",
  "name": "Praveen Lohar",
  "email": "[email protected]",
  "password": "$2a$12$031HBBwJSaAzZ8TK4jkqTOBI0jUQcUuKbMk2UPZyFLRmWlFveJBZm",
  "cardsArray": [
    {
    "isFavourite": false,
    "_id": "60202538445530b28525df55d",
    "user": "Thor ",
    "bank": "Bank of Asgard",
    "cardNo": "551157766323",
    "expiry": "02/35",
    "cvv": "522325",
    "pin": "23",
},
  , {
      "isFavourite": false,
      "_id": "602025380475d30b2840dd84",
      "user": "Pepper Pots",
      "bank": "Bank of NewYork",
      "cardNo": "578454412312121",
      "expiry": "02/35",
      "cvv": "525",
      "pin": "45455",
  }],

  "loginIdsArray": [
    {
      "isFavourite": false,
      "_id": "602004abef310e0ee4c36319",
      "website": "Google",
      "username": "stark.Server122",
      "password": "55412pponj88"
  }, {
      "isFavourite": true,
      "_id": "60200fb9e79d5126b45594eb",
      "website": "Facebook",
      "username": "[email protected]",
      "password": "545121fdfnjfdnfdkjnd"
  }, {
      "isFavourite": false,
      "_id": "602013c570b26d0fdcb17a7e",
      "website": "Github",
      "username": "[email protected]",
      "password": "545121fdfnjfdnfdkjnd"
  }, {
      "isFavourite": true,
      "_id":"602013d570b26d0fdcb17a7f",
      "website": "Instagram",
      "username": "[email protected]",
      "password": "545121fdfnjfdnfdkjnd"
  }],
  "__v": {
      "$numberInt": "0"
  }
}

Upvotes: 0

Views: 38

Answers (1)

Richard Scarrott
Richard Scarrott

Reputation: 7033

Your aggregation looks fine -- as demo'd here https://mongoplayground.net/p/GX-k5W4Pbhe

It therefore looks like it's not finding the document. Perhaps you're using native ObjectIDs for your _id and not a string so your $match query should be:

{ $match: { _id: mongoose.Types.ObjectId(req.query.user_id) } }

As documented here https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

Upvotes: 1

Related Questions