簡體   English   中英

如何在 mongoDB 中檢查對象數組中的 2 個元素是否具有相同的值?

[英]How to check if 2 elements inside an array of objects have the same value, in mongoDB?

我的users收集數據在 mongoDB 中如下所示:

_id: ObjectId,
sports: [
  {
    name: 'cricket',
    history: [
      {
        from: 10,
        to: 30
      },
      {
        from: 30,
        to: 30
      }
    ]
  },
  // ... other sports as well
]

我要查詢的是所有在sports.history中具有滿足此條件的匹配元素的用戶: from === to (用戶可以有多個運動,每個運動都有自己的歷史)。 我試圖在查詢中實現這一點,而不是將用戶帶入我的快速應用程序並在之后過濾它們。

任何幫助深表感謝。 謝謝!

使用$expr運算符,您可以使用各種數組運算符查詢集合。 考慮首先使用$reduce展平二維數組 '$sports.history' :

 {
    $reduce: {
        input: "$sports.history",
        initialValue: [],
        in: { $concatArrays: [ "$$value", "$$this" ] }
    }
}

並使用$filter在給定條件下過濾縮減的數組

{ $filter: {
    input: {
        $reduce: {
            input: "$sports.history",
            initialValue: [],
            in: { $concatArrays: [ "$$value", "$$this" ]
            }
        }
    },
    cond: {
        $eq: ['$$this.from', '$$this.to']
    }
} }

使用$size檢查上述表達式產生的數組的長度:

{ $size: { 
    { $filter: {
        input: {
            $reduce: {
                input: '$sports.history',
                initialValue: [],
                in: { $concatArrays: [ '$$value', '$$this' ] }
            }
        },
        cond: {
            $eq: ['$$this.from', '$$this.to']
        }
    } }
} }

如果過濾數組的長度大於零,則用戶存在:

{ $gt: [
    { $size: { 
        $filter: {
            input: {
                $reduce: {
                    input: "$sports.history",
                    initialValue: [],
                    in: { $concatArrays: [ "$$value", "$$this" ] }
                }
            },
            cond: {
                $eq: ['$$this.from', '$$this.to']
            }
        }
    } },
    0
] }

總體而言,您的最終查詢應如下所示:

db.users.find({
    $expr: {
        $gt: [
            { $size: {
                $filter: {
                    input: {
                        $reduce: {
                            input: "$sports.history",
                            initialValue: [],
                            in: { $concatArrays: [ "$$value", "$$this" ] }
                        }
                    },
                    cond: {
                        $eq: ['$$this.from', '$$this.to']
                    }
                }
            } },
            0
        ]
    }
})

蒙戈游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM