Shaishab Roy
Shaishab Roy

Reputation: 16805

Can I find documents based on populate condition in mongoDB?

I want to find those orders that customer first name like 'john'. want to use only mongo query.

I have a order collection like:

{ 
    "_id" : ObjectId("5669891a49b065ae2d7a5ea7"), 
    "customer" : ObjectId("563a399a11c9b15001565463"),
    "quantity" : "6"
}

my query:

var page = req.query.page || 1;
    var limit = req.query.limit || 20;
    var skip  = (page - 1) * limit;
var populateSearchQuery = { firstName: { '$regex': 'john', '$options': 'i' } }

Order.find({})
        .skip(skip).limit(limit)
        .populate('customer','firstName lastName', populateSearchQuery)
        .exec(function(error, orders) {
            if(error) {
                return res.status(400).send({msg: 'Error occurred while getting orders.'});
            }
        return res.status(200).send(orders);
        });

I got all orders but populate only matched condition customer. want only matched condition orders.

Is there any way to find only using mongo query?

Upvotes: 2

Views: 356

Answers (1)

Derek Soike
Derek Soike

Reputation: 11650

I don't believe this is possible. You could get there with an Aggregation Operation, but you'd still be getting all the docs and then sorting through them. Your best bet is probably just a 2 step query operation.

  1. Get the ids for all the customers with a first name of john.
  2. Get the orders that map to those customers.

Customer.find({firstName: 'john'})
    .select('_id')
    .exec(function(err, customerDocs) {
        if (err) {...}
        var customerIds = [];
        for (var i=0; i<customerDocs.length; i++) {
            customerIds.push(customerDocs[i]._id);                                     
        }
        Order.find({customer: {$in: customerIds}})
             .exec(function(err, orderDocs) {...});
    });

Upvotes: 1

Related Questions