获取数组值的一部分

超级英雄

我在数据库中有一个对象,看起来像:

{
  'name':  'foo',
  'table':
  [
    {
      'date' : ISODate("2000-01-13T23:00:00Z")
    },
    {
      'date' : ISODate("2000-01-14T23:00:00Z")
    },
    {
      'date' : ISODate("2000-01-15T23:00:00Z")
    },
    {
      'date' : ISODate("2000-01-16T23:00:00Z")
    },
    {
      'date' : ISODate("2000-01-17T23:00:00Z")
    }
  ]
}

我希望查询以下结果:

{
  'name':  'foo',
  'table':
  [
    {
      'date' : ISODate("2000-01-15T23:00:00Z")
    },
    {
      'date' : ISODate("2000-01-16T23:00:00Z")
    }
  ]
}

因此,我正在寻找一种提取两个不同日期之间的子代的方法。


到目前为止,我已经尝试了以下方法:

db.stock.find({'table.date' : {$gte : '2000-01-15', $lt : '2000-01-17'}});

db.stock.find({'table.date' : {$gte : new Date('2000-01-15'), $lt : new Date('2000-01-17')}});

db.stock.find({'table.date' : {$gte : '2000-01-15T23:00:00Z', $lt : '2000-01-17T23:00:00Z'}});

db.stock.find({'table.date' : {$gte : ISODate('2000-01-15T23:00:00Z'), $lt : ISODate('2000-01-17T23:00:00Z')}});

db.stock.find({'table.date' : {$gte : new Date('2000-01-15T23:00:00Z'), $lt : new Date('2000-01-17T23:00:00Z')}});

这可能吗?如果是这样,如何解决?

尼尔·伦恩

本身无法.find()“过滤”数组的返回元素。您可以使用具有匹配条件位置$运算符来仅“投影”一个匹配元素(请参见文档)。

这里的原因是这里的查询是匹配的数组元素,而是文件“包含”匹配的数组元素。

但是要将元素“过滤”为所需元素,您需要使用aggregate

db.stock.aggregate([
  // Matching first is a good idea to filter the documents that contain
  // the matching elements
  { "$match": { 
      "table.date": { 
          "$gte": new Date("2000-01-15"), 
           "$lt": new Date("2000-01-17")
      }
   }},              

   // Unwind the array, this "de-normalizes"
   { "$unwind": "$table" },

  // Now use the match to actually "filter" results in the array
  { "$match": { 
      "table.date": { 
          "$gte": new Date("2000-01-15"), 
           "$lt": new Date("2000-01-17")
      }
   }},              

   // Group the results back by a "key", probably the document
   { "$group": {
       "_id": "$_id",
       "table": { "$push": "$table" }
   }}

])

从示例中还值得注意的是,您需要使用日期作为实际的日期类型,而不是“字符串”。在其他语言实现中也是如此,在该实现中,本机日期类型将作为BSON日期发送到MongoDB服务器,可以在内部对其进行比较。

有关使用这种类型的查询返回原始文档表单的更多信息,请参见此处

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章