MongoDB - Query conundrum - Document refs or subdocument MongoDB - Query conundrum - Document refs or subdocument mongoose mongoose

MongoDB - Query conundrum - Document refs or subdocument


There is another option (besides embedding and normalizing) for storing hierarchies in mongodb, that is storing them as tree structures. In this case you would store Buyers and Items in separate documents but in the same collection. Each Item document would need a field pointing to its Buyer (parent) document, and each Buyer document's parent field would be set to null. The docs I linked to explain several implementations you could choose from.


If your items are stored in two separate collections than the best option will be write your own function and call it using mongoose.connection.db.eval('some code...');. In such case you can execute your advanced logic on the server side.

You can write something like this:

var allNearItems = db.Items.find(    { location: {        $near: {            $geometry: {              type: "Point" ,              coordinates: [ <longitude> , <latitude> ]            },            $maxDistance: 100        }    }}); var res = [];allNearItems.forEach(function(item){    var buyer = db.Buyers.find({ id: item.buyerId })[0];    if (!buyer) continue;    if (item.bid < buyer.credit) {        res.push(item.id);    }});return res;

After evaluation (place it in mongoose.connection.db.eval("...") call) you will get the array of item id`s.

Use it with cautions. If your allNearItems array will be too large or you will query it very often you can face the performance problems. MongoDB team actually has deprecated direct js code execution but it is still available on current stable release.