我有一個 MongoDB 集合,其中包含如下檔案:
{
"_id": ObjectId(.....),
"name": "John",
"contacts": [
{
"name": "henry",
"age": "22"
},
{
"name": "merry",
"age": "12"
}
]
}
我想查找contacts.age少于 20 個的檔案。我嘗試了以下 mongo 查詢,但沒有運氣。任何人都可以幫助我嗎?
document.Users.find({'$expr':{'$lte': [{'$toInt':'$contacts.age'}, '20'] }})
上面的查詢給出了以下錯誤:
Query failed with error code 241 and error message 'Executor error during find command ::
caused by ::
Unsupported conversion from array to int in $convert with no one rror value' on server
uj5u.com熱心網友回復:
如果您想要所有檔案(不做任何更改),您可以嘗試以下聚合查詢:
true這里的技巧是只獲取從條件回傳的陣列中有一個檔案"$lte": [{"$toInt": "$$this"},20]。
這意味著只有具有匹配值(至少一個子檔案)的陣列的匹配檔案才會匹配。
使用最終的作業示例進行編輯,使用兩種方法來確保資料:
- 在 the 之前使用
"contacts": { "$ne": null }into stage以避免 map over null。$match$expr - 使用$convert可以在任何值不是數字
onError且onNull無法轉換的情況下使用。
db.collection.aggregate([
{
"$match": {
"contacts": {
"$ne": null
},
"$expr": {
"$in": [
true,
{
"$map": {
"input": "$contacts",
"in": {
"$lte": [
{
"$convert": {
"input": "$$this.age",
"to": "int",
"onError": "",
"onNull": ""
}
},
30
]
}
}
}
]
}
}
}
])
這里的例子
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430452.html
