简体   繁体   中英

How to query neighbor elements in MongoDB?

I am implementing a ranking system. I have a collection with elements like this:

{"_id" : 1, "count" : 32}
{"_id" : 2, "count" : 12}
{"_id" : 3, "count" : 34}
{"_id" : 4, "count" : 9}
{"_id" : 5, "count" : 77}
{"_id" : 6, "count" : 20}

I want to write a query that return an element which has {"id" : 1} and 2 other neighbor elements (after sorting by count). Totally 3 elements returned.

Ex: After sorting:

9 12 20 32 34 77

The query should return 20 32 34 .

You will never get this in a single query operation, but it can be obtained with "three" queries. The first to obtain the value for "count" from the desired element, and the subsequent ones to find the "preceding" and "following" values.

var result = [];
var obj = db.collection.findOne({ "_id": 1 }); // returns object as selected
result.push(obj);
// Preceding 
result.unshift(db.collection.findOne({ 
    "$query": { "count": { "$lt": obj.count } },
    "$orderby": { "count": -1 }
}));
// Following
result.push(db.collection.findOne({ 
    "$query": { "count": { "$gt": obj.count } },
    "$orderby": { "count": 1 }
}));

Asking to do this in a "single query" is essentially asking for a "join", which is something that MongoDB essentially does not do. It is a "Set Intersection" of the discrete results, and that in SQL is basically a "join" operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM