假設我有作為 userDetails 的檔案:
[
{
"roles": [
"author",
"reader"
],
"completed_roles": ["author", "reader"],
"address": {
"current_address": {
"city": "abc"
}
},
"is_verified": true
},
{
"roles": [
"reader"
],
"completed_roles": ["reader"],
"address": {
"current_address": {
"city": "abc"
}
},
"is_verified": true
},
{
"roles": [
"author"
],
"completed_roles": [],
"address": {
"current_address": {
"city": "xyz"
}
},
"is_verified": false
}
]
我想獲取所有角色的總和,這些角色的作者基于城市、total_roles_completed 和 is_verified。
所以 O/P 應該是這樣的:
[
{
"_id": {
"city": "abc"
},
"total_author": 1,
"total_roles_completed": 1,
"is_verified": 1
},
{
"_id": {
"city": "xyz"
},
"total_author": 1,
"total_roles_completed": 0,
"is_verified": 0
}
]
所需的基本 O/P:
- 根據角色中的作者過濾檔案(角色中可能存在其他角色,但作者必須存在)
- 根據城市對作者求和
- 基于 completed_profile 的總和具有“作者”
- 如果檔案經過驗證,則根據檔案進行匯總。
為此,我嘗試如下:
db.userDetails.aggregate([
{
$match: {
roles: {
$eleMatch: {
$eq: "author"
}
}
}
},
{
$unwind: "$completed_roles"
},
{
"$group": {
_id: { city: "$address.current_address.city"},
total_authors: {$sum: 1},
total_roles_completed: {
$sum: {
$cond: [
{
$eq: ["$completed_roles","author"]
}
]
}
},
is_verified: {
$sum: {
$cond: [
{
$eq: ["$is_verified",true]
}
]
}
}
}
}
]);
但總和是不正確的。請讓我知道我在哪里犯了錯誤。另外,如果有人需要任何進一步的資訊,請告訴我。
編輯:我認為由于 unwind 它給了我不正確的值,如果我洗掉 unwind 總和是正確的。
有沒有其他方法可以計算每個城市的 total_roles_completed 總和?
uj5u.com熱心網友回復:
如果我理解正確,您可以嘗試以下查詢:
- 首先
$match只獲取roles包含author. - 然后
$group按城市(該檔案不是有效的 JSON,所以我假設是address:{"current_addres:{city:"abc"}})。這$group將獲取每個城市的作者以及:$sum1 如果“作者”在completed_roles其中并檢查是否已驗證。
在這里我不知道如何知道作者是否經過驗證(我不知道在一個檔案中是否可以為真,在另一個檔案中為假。如果所有檔案的值相同,您可以使用它$first來獲取第一個is_verified值)。但是我決定$allElementsTrue在一個$project階段使用,所以只有is_verified在所有由$group.
db.collection.aggregate([
{
"$match": {
"roles": "author"
}
},
{
"$group": {
"_id": "$address.current_address.city",
"total_author": {
"$sum": 1
},
"total_roles_completed": {
"$sum": {
"$cond": {
"if": {
"$in": [
"author",
"$completed_roles"
]
},
"then": 1,
"else": 0
}
}
},
"is_verified": {
"$addToSet": "$is_verified"
}
}
},
{
"$project": {
"_id": 0,
"city": "$_id",
"is_verified": {
"$allElementsTrue": "$is_verified"
},
"total_author": 1,
"total_roles_completed": 1
}
}
])
這里的例子
此查詢的結果是:
[
{
"city": "xyz",
"is_verified": false,
"total_author": 1,
"total_roles_completed": 0
},
{
"city": "abc",
"is_verified": true,
"total_author": 2,
"total_roles_completed": 2
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422853.html
標籤:
