Combine two collections with a range Condition

2020-04-30 16:23发布

问题:

I have a collection "product" with documents like these :

{"_id" : 142347106,"name" : "product 1"}
{"_id" : 135377126,"name" : "product 2"}

I have an other collection "price" :

{
    "_id" : ObjectId("59310a6bad6e99863c2a6860"),
    "region" : 1111,
    "price" : 7.6,
    "id_start" : 174683814,
    "id_end" : 174686813,
    "qte" : 3000
}

The price of a prodct can be found with the _id of product which is between "id_start" and "id_end". So if I want to have the price of all products I can do the following query :

db.getCollection("product").find({}).forEach( function(myProduct) {
     db.getCollection("price").findOne({$and: [ { "id_start":{$lt: parseInt(myProduct._id) } }, {"id_end":{$gt: parseInt(myProduct._id)}}]})
});

This is working but my problem is I have a lot of documents, and when I run the query it always end with a "errmsg" : "Cursor not found, cursor id: ...

So I would like to find an other way to query, by using the aggregation framework for example.

Do you have idea ?

I could combine the two collections in one to aggregate but I don't really like the way :-/

Thank you very much !