Get a subdocument from document with criteria Mongodb Dart

822

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();
Share:
822
Onur
Author by

Onur

Updated on November 20, 2022

Comments

  • Onur
    Onur over 1 year

    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

  • Onur
    Onur over 4 years
    You cannot do that in mongo dart. When I write this code it gives me error: "Too many positional arguments: 1 expected, but 2 found. Try removing the extra arguments." findOne() function only getting Map or Selector Builder and one argument.
  • Ayoub
    Ayoub over 4 years
    your projection will return all workers for the matching filter
  • Onur
    Onur over 4 years
    Also second option didn't work. It throw error:"Exception: Not implemented for SelectorBuilder({$query: {companyMail: [email protected]}})" ?