0

I have two documents, buyers and submission (submissions are a subdocument of buyers).

mongoose.model('Buyer',{
    username: String,
    credit: Number,
    forms:[mongoose.model('Submission').schema]
});

and

mongoose.model('Submission',{
    title: String,
    bid: Number,
});

Each buyer has a credit attribute and each submission has a bid attribute. I want to build a query that will search for any submission where the bid is lower than its parent.credit

Is it possible to find based on the comparison of parent-child attributes?

jordan
  • 9,570
  • 9
  • 43
  • 78

1 Answers1

2

You cannot compare two fields (be it subdocuments or not) in mongodb using normal find queries (unless you use the $where, but be aware that it is quite slow because it executes that javascript for each document).

However, what you want is possible with the aggregation pipeline:

db.buyers.aggregate([
    {$unwind: "$forms"},
    {$project: {
        username : 1,
        credit : 1,
        forms : 1,
        lower : {"$cond" : [{$lt: [ '$forms.bid', '$credit']}, 1, 0]}
    }},
    {$match : {lower : 1}}
]);

This will get you the entries where the bid is lower than the credit.

Community
  • 1
  • 1
joao
  • 4,067
  • 3
  • 33
  • 37