我將 NestJS 與 Mongoose 一起使用,我有 2 個集合、區域和診所
首先我搜索用戶附近的地區
async findAllByLocation(location: Location) {
const territories = await this.territoryModel.find({
location: {
$near: {
$geometry: {
type: 'Point',
coordinates: [location.lat, location.long],
},
},
},
});
return territories.map((territory) => {
return {
_id: territory._id,
name: territory.name,
};
});
}
然后診所服務利用此函式從回傳的陣列中獲取具有任何區域的診所
async getClinicsByLocation(location: any): Promise<any> {
const territories = await this.territoryService.findAllByLocation(location);
const clinics = await this.clinicModel.find({
territory: { $in: territories.map((t) => t._id) },
});
return clinics;
}
我現在的問題是區域陣列是從最近到最遠的順序排序的,但是診所的順序是隨機的,因此診所在回應中的領土比其他診所更遠
一種解決方案是在每個區域單獨建立診所,然后合并陣列,但這不是時間或性能效率
任何的想法 ?
uj5u.com熱心網友回復:
我認為您可以在一個聚合查詢中做到這一點。輸入和輸出示例也將有所幫助。
順便說一句,對于您的查詢,我認為您想要:
- 讓所有地區靠近一個位置
- 只回傳
_idandname - 搜索與from
territory相同的診所。_idterritories
所以我認為這可以在一個這樣的查詢中完成:
db.territories.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [location.lat, location.long]
},
distanceField: "dist.calculated"
}
},
{
$project: {
name: 1
}
},
{
$lookup: {
from: "clinics",
localField: "_id",
foreignField: "territory",
as: "clinics"
}
},
{
$unwind: "$clinics" // optional; it depends the output you want
}
])
結果是這樣的:
{
"_id":2,
"name":"territory name 2",
"clinics":{
"_id":ObjectId("61ea8a20f90aaa6f3e23efac"),
"territory":2,
"name":"clinic2"
}
}{
"_id":1,
"name":"territory name 1",
"clinics":{
"_id":ObjectId("61ea8a20f90aaa6f3e23efab"),
"territory":1,
"name":"clinic1"
}
}{
"_id":3,
"name":"territory name 3",
"clinics":{
"_id":ObjectId("61ea8a20f90aaa6f3e23efad"),
"territory":3,
"name":"clinic3"
}
}
我使用mongo $geoNear 示例作為輸入資料,并且在所有執行中,順序都是相同的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/417621.html
標籤:
上一篇:階乘的模除以階乘
