我使用 MongoDB 并且我有這樣一個集合。首先,我選擇tableId = 1 的所有檔案,然后按itemId 將它們分組- 我得到 2 組,每組 2 個檔案。總而言之,我需要離開有這樣檔案的組:1)城市=倫敦,2)年份大于或等于某個值。為此,我需要將值從字串轉換為數字。如何才能做到這一點?
在我下面的查詢中,比較年份的部分是錯誤的。
[
{
"tableId": 1,
"itemId": 10,
"name": "City",
"value": "London"
},
{
"tableId": 1,
"itemId": 10,
"name": "StartYear",
"value": "2017"
},
{
"tableId": 1,
"itemId": 20,
"name": "City",
"value": "Paris"
},
{
"tableId": 1,
"itemId": 20,
"name": "StartYear",
"value": "2018"
},
{
"tableId": 2,
"itemId": 30,
"name": "City",
"value": "Madrid"
},
{
"tableId": 2,
"itemId": 30,
"name": "StartYear",
"value": "2016"
}
]
我的查詢是:
db.collection.aggregate([
{
"$match": {
tableId: 1
}
},
{
"$group": {
_id: {
itemId: "$itemId"
},
result: {
$push: "$$ROOT"
}
}
},
{
"$match": {
$and: [
{
"result": {
$elemMatch: {
"name": "City",
"value": "London"
}
}
},
{
"result": {
$elemMatch: {
$and: [
{
"name": "StartYear"
},
{
$lte: [
{
$toDouble: "$value"
},
2018
]
}
]
}
}
}
]
}
}
])
uj5u.com熱心網友回復:
您可以先進行條件映射,以使用$mapfirst將年份轉換為數值。然后執行您的$elemMatch標準。
db.collection.aggregate([
{
"$match": {
tableId: 1
}
},
{
"$addFields": {
"value": {
"$cond": {
"if": {
$eq: [
"$name",
"StartYear"
]
},
"then": {
$toInt: "$value"
},
"else": "$value"
}
}
}
},
{
"$group": {
_id: {
itemId: "$itemId"
},
result: {
$push: "$$ROOT"
}
}
},
{
"$match": {
$and: [
{
"result": {
$elemMatch: {
"name": "City",
"value": "London"
}
}
},
{
"result": {
$elemMatch: {
"name": "StartYear",
"value": {
$lte: 2018
}
}
}
}
]
}
}
])
這是Mongo 游樂場供您參考。
uj5u.com熱心網友回復:
詢問
- 分組并計數如果
name/value找到,如果startYear/value找到 - 保留那些都找到的
- 取消設定 2 個臨時欄位
cityFound,yearFound
測驗代碼在這里
aggregate(
[{"$match":{"$expr":{"$eq":["$tableId", 1]}}},
{"$group":
{"_id":"$itemId",
"cityFound":
{"$sum":
{"$cond":
[{"$and":
[{"$eq":["$name", "City"]}, {"$eq":["$value", "London"]}]},
1, 0]}},
"yearFound":
{"$sum":
{"$cond":
[{"$and":
[{"$eq":["$name", "StartYear"]},
{"$lte":[{"$toInt":"$value"}, 2018]}]},
1, 0]}},
"result":{"$push":"$$ROOT"}}},
{"$match":
{"$expr":
{"$and":[{"$gt":["$cityFound", 0]}, {"$gt":["$yearFound", 0]}]}}},
{"$unset":["cityFound", "yearFound"]}])
上面的速度很快,因為它在分組時進行檢查。
要將字串轉換為數字,我們可以執行$toIntor toDouble。但那些是聚合運算子,在匹配中它們應該在$expr.
您的查詢的問題在于您在查詢運算子中使用聚合運算式,這不起作用,例如$value聚合運算式,$toDouble您也不能同時使用兩者。
代替 elem-match,您可以使用$filter允許內部聚合運算式,并檢查過濾器陣列是否為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391906.html
