我有看起來像這樣的物件
{
name: 'Object 1',
fruitList: ['apple','pear','orange','grape']
},
{
name: 'Object 2',
fruitList: ['melon','pear','apple','kiwi']
}
我需要檢索apple之前pear在它們的所有物件fruitList,在這個例子中,它只是意味著Object 1。我可以做一個自定義匹配函式來迭代該串列并檢查它是否符合我的條件?
uj5u.com熱心網友回復:
您需要一種機制來比較相關水果的索引,并將比較用作$expr運算子的匹配條件。利用聚合管道運算子:
$indexOfArray- 在陣列中搜索指定值的出現并回傳第一次出現的陣列索引(從零開始)。$subtract- 回傳兩個索引之間的差異。如果該值為負數,則 apple 將出現在串列中 pear 之前。$lt- 在查詢中使用的比較運算子$expr比較兩個值并在第一個值小于第二個值時回傳 true。
要大致了解這些運算子在聚合管道中的作用,請查看以下Mongo Playground。
您需要的實際查詢如下:
db.collection.find({
$expr: {
lt: [
{
$subtract: [
{ $indexOfArray: [ '$fruitList', 'apple' ] },
{ $indexOfArray: [ '$fruitList', 'pear' ] }
]
},
0
]
}
})
蒙戈游樂場
對于基于通用正則運算式的解決方案,其中fruitList陣列可能包含一籃子什錦水果(在不同情況下),例如:
"fruitList" : [
"mango",
"Apples",
"Banana",
"strawberry",
"peach",
"Pears"
]
以下查詢可以解決這一挑戰:
const getMapExpression = (fruit) => {
return {
$map: {
input: '$fruitList',
as: 'fruit',
in: {
$cond: [
{ $regexMatch: { input: '$$fruit', regex: fruit, options: 'i' } },
{ $literal: fruit },
'$$fruit'
]
}
}
}
}
db.collection.find({
$expr: {
$lt: [
{
$subtract: [
{ $indexOfArray: [ getMapExpression('apple'), 'apple' ] },
{ $indexOfArray: [ getMapExpression('pear'), 'pear' ] }
]
},
0
]
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440582.html
