我正在使用猫鼬,并有一个具有位置和最大距离的用户列表:
const userSchema = new mongoose.Schema({
maxDistance: { type: Number, default: 1000 },
location: {
type: {
type: String,
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
required: true,
},
},
});
我想做的是让所有用户接近一个我只知道_id的用户。 虽然我知道我可以使用javascript轻松做到这一点,但我想知道Mongo在单个请求中是否有可能。
我找到了类似this的答案:
db.collection.aggregate([
{ "$geoNear": {
"near": {
"type": "Point",
// those are raw values, i'd like to get coordinates of a user i'd find by _id
"coordinates": [ 23.027573, 72.50675800000001 ],
},
"distanceField": "distance"
}},
{ "$redact": {
"$cond": {
"if": { "$lte": [ "$distance", "$radius" ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
我想做的是
如果可能的话,在一个查询中,我想避免做两个事情,首先是findById,然后是上一个聚合。
有可能这样做吗?