midhun k
midhun k

Reputation: 1058

Mongo query using filter not fetching exact result?

My mongo table contains contains collection 'Shops' and data like the below:

{
    "ShopId" : 9999,
    "products" : [ 
        {
            "productId" : "1234",
            "productName" : "abcd",
        }, 
        {
            "productId" : "5678",
            "productName" : "abc",

        },
         {
            "productId" : "2345",
            "productName" : "def",

        }

    ],
}

There will be several shops in the table having a list of products.

Requirement:

I want to fetch the records having shopId=9999 and products matches the string abc

My query

model.Shops.aggregate([{$match:{"ShopId":9999}},{$project:{products:{$filter:{input:'$products',cond: {'productName':/abc/ }}}}}])

Problem:

It is fetching the productname:defwith the other data that matches productname:abc.

Upvotes: 0

Views: 125

Answers (2)

felix
felix

Reputation: 9285

You can't use regex search with the $filter operator. The only way to achieve this is to unwind products, filter document and then re-group them in an array

model.Shops.aggregate([
   {
      $match:{
         "ShopId":9999
      }
   },
   {
      $unwind:"$products"
   },
   {
      $match:{
         "products.productName":/abc/
      }
   },
   {
      $group:{
         _id:null,
         products:{
            $push:{
               "productName":"$products.productName",
               "productId":"$products.productId"
            }
         }
      }
   }
])

output:

{
   "_id":null,
   "products":[
      {
         "productName":"abcd",
         "productId":"1234"
      },
      {
         "productName":"abc",
         "productId":"5678"
      }
   ]
}

to use it with a variable, declare your regex like this:

var regex: /abc/;

and then use it directly in the query

   $match:{
         "products.productName": regex
      }

Upvotes: 1

Puneet Singh
Puneet Singh

Reputation: 3543

Below code worked on mongoshell for me, and your code was giving error to me, that Missing 'as' parameter to $filter.

db.Shops.aggregate([
{$match:{"ShopId":9999}},
{$project:{
    products:{$filter:{input:'$products',as:"product",cond: { $eq: [ "$$product.productName", "abc" ] }}}
    }}
])

Upvotes: 0

Related Questions