Get a subdocument from document with criteria Mongodb Dart

Issue

Hello I have json data like that:

{ 
   "_id":ObjectId('5dfe907f80580559fedcc9b1'),
   "companyMail":"mail@gmail.com"
   "workers":[ 
      { 
         "name":name,
         "surName":surname,
         "mail":"mail2@gmail.com",
         "password":"password",
         "companyMail":"mail@gmail.com",
      }
   ]

}

And I want to get an worker from workers:

 { 
     "name":name,
     "surName":surname,
     "mail":"mail2@gmail.com",
     "password":"password",
     "companyMail":"mail@gmail.com",
  }

I’m writing this query:

collection.findOne({
      'companyMail':"mail@gmail.com",
      'workers.mail':"mail2@gmail.com",

      });

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();

Answered By – Onur

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.