單人游樂場
我有以下帶有陣列(名稱gists)的檔案。檔案示例:
{
"_id": ObjectId("60a2c0621e5f043b735e36ef"),
"car_id": 78,
"terminal": "JFK",
"gists": [
"A",
"M",
"C",
"D",
"Q",
"J",
"F"
]
},
我的目標是查詢其中包含重復“A”的所有檔案并獲取它們的car_id.
雖然我可以找到重復項,但我無法在gists.
db.collection.aggregate([
{
"$project": {
"gists": 1
}
},
{
"$unwind": "$gists"
},
{
"$group": {
"_id": {
"_id": "$_id",
"cid": "$gists"
},
"count": {
"$sum": 1
}
}
},
{
"$match": {
"$and": [
{
"count": {
"$gt": 1
}
},
{
"gists": "A" **//<---- this is where I get it off. Gist must contain A in the array**
}
]
}
},
{
"$group": {
"_id": "$_id._id",
"gists": {
"$addToSet": "$_id.cid"
}
}
}
])
uj5u.com熱心網友回復:
您可以嘗試$expr使用聚合運算子的運算式運算子,
$filter迭代陣列回圈gists并檢查值“A”$size從以上過濾結果中獲取總元素$gt檢查上述大小是否大于 1$group通過 null 并構造陣列car_id
db.collection.aggregate([
{
$match: {
$expr: {
$gt: [
{
$size: {
$filter: {
input: "$gists",
cond: { $eq: ["$$this", "A"] }
}
}
},
1
]
}
}
},
{
$group: {
_id: null,
car_id: { $push: "$car_id" }
}
}
])
操場
結果:
[
{
"_id": null,
"car_id": [79, 80]
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414711.html
標籤:
