Get a subdocument from document with criteria Mongodb Dart

1.2k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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

Pass options to project the workers field only

   db.company.findOne(
     {
        'companyMail':"[email protected]",
        'workers.mail':"[email protected]",
      },
     {
         "workers":1,
         _id:0
     }
    );

In mongo-dart , looking at their api, you can use aggregation which is as follows

  final pipeline = AggregationPipelineBuilder()
    .addStage(Match(where.eq('companyMail','[email protected]')))
    .addStage(Project({
                  '_id': 0,
                  "workers":1,
                })).build())

  final result =
     await DbCollection(db, 'company')
       .aggregateToStream(pipeline).toList();
  // result[0] should give you one worker
0
On

mongo-dart API driver is very bad and there is no good documentation whereas mongo-node.js API driver is very good and has very good documentation, so better to do server side with node, for example in node your problem will solve by one line code:

    collection.find(
    {
      'companyMail':"[email protected]",
      'workers.mail':"[email protected]",
    }).project({
    '_id':0, 'workers':1
    });