Search code examples
mongodbflutterdartmongo-dart

Get a subdocument from document with criteria Mongodb Dart


Hello I have json data like that:

{ 
   "_id":ObjectId('5dfe907f80580559fedcc9b1'),
   "companyMail":"[email protected]"
   "workers":[ 
      { 
         "name":name,
         "surName":surname,
         "mail":"[email protected]",
         "password":"password",
         "companyMail":"[email protected]",
      }
   ]

}

And I want to get an worker from workers:

 { 
     "name":name,
     "surName":surname,
     "mail":"[email protected]",
     "password":"password",
     "companyMail":"[email protected]",
  }

I'm writing this query:

collection.findOne({
      'companyMail':"[email protected]",
      'workers.mail':"[email protected]",

      });

But it gives me whole of data. I only want to get worker which I search. How can I do that with Mongo Dart. https://pub.dev/packages/mongo_dart


Solution

  • I found the solution. We should use aggregation but we should add some specific query to get one result. In dart mongo, we can use Filter object to add. Like that:

                final pipeline = AggregationPipelineBuilder()
          .addStage(Match(where.eq('companyMail', companyMail).map['\$query']))
          .addStage(Match(where.eq('customers.mail', customerMail).map['\$query']))
          .addStage(Project({
            "_id": 0, //You can use as:'customer' instead of this keyword.
            "customers": Filter(input: '\$customers',cond: {'\$eq':["\$\$this.mail",customerMail]}).build(),
          }))
          .build();
      final result = await DbCollection(_db, 'Companies')
          .aggregateToStream(pipeline)
          .toList();