首页 > 解决方案 > 如何编写以下 MongoDB 查询

问题描述

假设我有以下foobar集合:

{
  "foobar": [
    {
      "_id": "abc",
      "history": [
        {
          "type": "foo",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        }
      ]
    },
    {
      "_id": "dfg",
      "history": [
        {
          "type": "baz",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        }
      ]
    },
    {
      "_id": "hij",
      "history": [
        {
          "type": "foo",
          "timestamp": 123456789.0
        },
        {
          "type": "bar",
          "timestamp": 123456789.0
        },
        {
          "type": "foo",
          "timestamp": 123456789.0
        }
      ]
    }
  ]
}

如何根据项目中的道具查询( $gte/ $lte)项目,但使用from the item where ?foobartimestamphistorytimestamptype: "foo"

如果没有type等于的子文档foo,则过滤掉整个文档,如果有多个type等于的子文档,foo则它可以匹配任何人。

标签: mongodbnosqlaggregation-framework

解决方案


您可以尝试以下聚合:

var threshold = 123456788;
db.foobar.aggregate([
    {
        $addFields: {
            foobar: {
                $filter: {
                    input: "$foobar",
                    as: "doc",
                    cond: {
                        $let: {
                            vars: { 
                                foo: {
                                    $arrayElemAt: [
                                        {
                                            $filter: {
                                                input: "$$doc.history",
                                                as: "history",
                                                cond: {
                                                    $eq: [ "$$history.type", "foo" ]
                                                }
                                            }
                                        },
                                        0]
                                }
                            },
                            in: {
                                $gt: [ "$$foo.timestamp", threshold ]
                            }
                        }
                    }
                }
            }
        }
    }
])

$addFields可用于覆盖现有字段 ( foobar)。要过滤掉所有与您的条件不匹配的子文档,您可以使用$filter(外部)。对于每个foobar文档,您可以使用$let来定义临时变量foo。您需要 inner$filter获取所有history元素 where typeisfoo然后$arrayElemAt获取第一个。然后你只需要$gt$lt应用你的比较。

对于那些没有的子文档,foo将被undefined返回,然后在$gt舞台上过滤掉。


推荐阅读