我有2個MongoDB集合,這里有2個模型例子:
用戶集合:
用戶集合:
{
_id: ObjectId,
available: Boolean。
province: String,
city: String,
[...]
}
Distances集合:
{
_id: ObjectId,
start_province: String,
start_city: String,
end_province: String,
end_city: String,
distance: Number, distance: Number
}
我需要的是使用類似{available.true}的查詢來找到Users。true},然后使用一些聚合來為每個用戶檔案添加一個distance欄位,如果在Users中的province和city與Distances中的end_province / end_city(start_province和start_city是在此堆疊之前的JS中定義的固定值),則將含有一個值。
如果有一個匹配的distance應該包含距離值,否則就是0(或未定義)。
我想我應該使用$lookup和/或$addFields,但是我對聚合運算子還沒有足夠的信心來解決這個問題。
用戶結果示例:
[
{
_id: ObjectId,
available: Boolean。
province: String,
city: String,
[...],
distance: Number
謝謝你的幫助!
EDIT: 按照要求添加了示例資料:
Users。
[
{name: 'John', available: true, province: 'Rome', city: 'Tivoli'}。
{name: 'Difool', available: true, province: 'Rome', city: 'Ostia'}。
{name: 'Paul', available: true, province: 'Rome', city: 'Rome'},
{name: 'Andrew', available: false, province: 'Rome', city: 'Grottaferrata'}。
]
距離 start_province: 'Rome', start_city: 'Rome', end_province: 'Rome', end_city: 'Ostia', distance: 5}。
{start_province: 'Rome', start_city: 'Rome', end_province: 'Rome', end_city: 'Tivoli', distance: 8}。
]
來自用戶的預期結果
[
{name: 'John', available: true, province: 'Rome', city: 'Tivoli', distance: 8}。
{name: 'Difool', available: true, province: 'Rome', city: 'Ostia', distance: 5}。
{name: 'Paul', available: true, province: 'Rome', city: 'Rome', distance: 0}。
]
過濾查詢。
{ available: true }用戶.省需要與Distance.end_province
相匹配。用戶.城市需要與Distance.end_city相匹配。
否則,distance應該回傳0或未定義。謝謝。
uj5u.com熱心網友回復:
查詢
- 過濾,以保持可用的 。
- 加入if
- 用戶的省份需要與Distance.end_province匹配 。
- 用戶的城市需要與Distance.end_city.相匹配 。
- 如果沒有加入 => distance=0 else 從第一個加入的檔案中獲取距離
- unset the distances(the join result)
*如果你有mongodb <5和索引,如果你能用$eq查詢運算子使第二個匹配,而不是我用的聚合$eq (它是一樣的,只是去掉了$expr,使用查詢$eq)
。db.users.aggregate( [
{
"$match"/span>: {
"available": {
"$eq": true。
}
}
},
{
"$lookup": {
"from": "distances",
"let": {
"uprovince": "$province",
"ucity": "$city".
},
"pipeline": [
{
"$match"/span>: {
"$expr": {
"$and": [
{
"$eq": {
"$$uprovince",
"$end_province".
]
},
{
"$eq": [
"$ucity",
"$end_city".
]
}
]
}
}
}
],
"as": "distances".
}
},
{
"$set": {
"distance": {
"$cond": [
{
"$eq": {
"$distances",
[]
]
},
0,
{
"$arrayElemAt": [
"$distances.distance",
0.
]
}
]
}
}
},
{
"$unset": [
"distances": "unset".
]
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/324672.html
標籤:
上一篇:將主要游戲回圈轉化為功能
