如何在 MongoDB 中找到具有所有值型別或某些值的檔案?
我在檔案中有一些欄位,我想用作過濾器來過濾檔案。
例子:-
人員欄位可以采用以下值之一:-[Person A, Person B, Person C,....]
型別欄位可以采用以下值之一:-[Type A, Type B, Type C]
源欄位可以采用以下值之一:-[Source A, Source B, Source C]
我想結合使用上述欄位來過濾檔案。
上述領域should be filtered as All or some specific value的領域。
我的意思是
對于查詢,我想要源 B的所有型別 A的人。
對于另一個查詢,我可能想要源 C的所有型別的人 B。
等等...
我想使用查詢中組合的所有欄位來過濾檔案。
你如何在 MongoDB 中實作這一點?
資料集:-
{
"_id": "1",
"Person": "Person A",
"type": "Type A",
"source": "Source A",
"subject": "some subject"
},
{
"_id": "2",
"Person": "Person B",
"type": "Type B",
"source": "Source C",
"subject": "some subject"
},
{
"_id": "3",
"Person": "Person C",
"type": "Type A",
"source": "Source A",
"subject": "some subject"
},
{
"_id": "4",
"Person": "Person C",
"type": "Type C",
"source": "Source B",
"subject": "some subject"
},
{
"_id": "5",
"Person": "Person A",
"type": "Type B",
"source": "Source A",
"subject": "some subject"
},
{
"_id": "6",
"Person": "Person B",
"type": "Type C",
"source": "Source A",
"subject": "some subject"
}
示例過濾器查詢 1:-
人:所有(即A,B,C)
型別:A
來源:A
查詢 1 的預期輸出:-
獲取具有id:- 1 和 3的檔案 Coz only ids 1&3 have Type and Source as A
示例過濾器查詢 2:-
人:A
型別:全部
來源:全部
查詢 2 的預期輸出:-
獲取具有id:- 1 和 5的檔案 coz person A has documents 1 & 5 associated with him.
示例過濾器查詢 3:-
人:所有
型別:全部
來源:乙
查詢 2 的預期輸出:-
獲取具有id:- 4的檔案 coz only id 4 has source as B
uj5u.com熱心網友回復:
在使用 執行查詢時,當提供的引數為“All”時$eq,您可以使用$or“轉義”查詢。
db.collection.aggregate([
{
"$addFields": {
// put your query param here
"paramPerson": "All",
"paramType": "Type A",
"paramSource": "Source A"
}
},
{
$match: {
$expr: {
$and: [
{
$or: [
{
$eq: [
"$paramPerson",
"All"
]
},
{
$eq: [
"$paramPerson",
"$Person"
]
}
]
},
{
$or: [
{
$eq: [
"$paramType",
"All"
]
},
{
$eq: [
"$paramType",
"$type"
]
}
]
},
{
$or: [
{
$eq: [
"$paramSource",
"All"
]
},
{
$eq: [
"$paramSource",
"$source"
]
}
]
}
]
}
}
},
{
"$project": {
"paramPerson": false,
"paramSource": false,
"paramType": false
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/460594.html
標籤:javascript 节点.js mongodb 表示 mongodb查询
下一篇:使用正則運算式后設定新值
