【问题标题】:MongoDB, finding documents by matching sub elements in an array by several Date conditions [duplicate]MongoDB,通过几个日期条件匹配数组中的子元素来查找文档[重复]
【发布时间】:2019-12-17 13:56:42
【问题描述】:

我有这样的文件:

{
  "_id": ID,
  "seen_at" : [ 
      ISODate("2018-12-27T17:00:00.000Z"), 
      ISODate("2019-01-01T01:00:00.000Z")
  ]
}

我尝试根据对seen_at 元素的查询来选择文档:

db.collection.aggregate(
  [
    {
      "$match": { 
        seen_at: {
            "$gt": ISODate("2019-01-01T00:00:00.000Z"),
            "$lt": ISODate('2019-01-01T00:00:00.001Z')
        }
      }  
    }
  ]
 )

我希望此查询仅查找 seen_at 中的元素同时满足两个条件的文档。

但是上面的查询返回了top-above 文档(其中也不匹配两个条件)

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    如果要从数组中查找多个条件,请使用 $elemMatch

    db.collection.find({
      seen_at: {
        $elemMatch: {
          "$gt": ISODate("2019-01-01T00:00:00.000Z"),
          "$lt": ISODate("2019-01-01T00:00:00.001Z")
        }
      }
    })
    

    Mongo Playground 中查看find 的结果。

    如果必须使用Aggregate,可以使用$unwind运算符:

    db.collection.aggregate([
    {
        $unwind : "$seen_at"
    },
    {
        "$match": { 
            seen_at: {
                "$gt": ISODate("2019-01-01T00:00:00.000Z"),
                "$lt": ISODate('2019-01-01T00:00:00.001Z')
            }
        }  
    },
    {
        $group : {
            "_id" : "$_id",
            "seen_at" : {$push : "$seen_at"}
        }
    }
    ])
    

    Mongo Playground 中查看Aggregate 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2015-07-01
      • 1970-01-01
      • 2018-04-11
      • 2016-02-17
      • 2015-02-09
      • 1970-01-01
      相关资源
      最近更新 更多