Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在mongodb的内部数组中返回部分数组匹配?_Mongodb_Nosql - Fatal编程技术网

如何在mongodb的内部数组中返回部分数组匹配?

如何在mongodb的内部数组中返回部分数组匹配?,mongodb,nosql,Mongodb,Nosql,我展示了mongodb集合文档结构的一个示例。在进行查询时,我也显示了我的预期结果 文件结构:: { _id : "132423423", name : "hi_code", my_entries : [ { e_id : "12345", e_name : "f1", e_posted : "2010-05-01", }, { e_id

我展示了mongodb集合文档结构的一个示例。在进行查询时,我也显示了我的预期结果

文件结构::

{ 
  _id : "132423423", 
  name : "hi_code", 
  my_entries : [ 
        { 
          e_id : "12345", 
          e_name : "f1", 
          e_posted : "2010-05-01", 
        }, 
        { 
          e_id : "12346", 
          e_name : "f2", 
          e_posted : "2010-06-01", 
        }, 
        { 
          e_id : "12346", 
          e_name : "f3", 
          e_posted : "2010-03-02", 
        } 
   ] 
} 
db.myCollection.find( { my_entries : { $elemMatch : { e_posted : "2010-06-01", 
e_name : "f2" } } } ) 
查询结构::

{ 
  _id : "132423423", 
  name : "hi_code", 
  my_entries : [ 
        { 
          e_id : "12345", 
          e_name : "f1", 
          e_posted : "2010-05-01", 
        }, 
        { 
          e_id : "12346", 
          e_name : "f2", 
          e_posted : "2010-06-01", 
        }, 
        { 
          e_id : "12346", 
          e_name : "f3", 
          e_posted : "2010-03-02", 
        } 
   ] 
} 
db.myCollection.find( { my_entries : { $elemMatch : { e_posted : "2010-06-01", 
e_name : "f2" } } } ) 
预期结果::

{ 
  _id : "132423423", 
  name : "hi_code", 
  my_entries : [ 
        { 
          e_id : "12346", 
          e_name : "f2", 
          e_posted : "2010-06-01", 
        }
   ] 
} 

我不想为此使用map reduce,因为我正在处理大型数据库,这会降低性能,只想通过查找查询使其成为可能。

您的实际结果是与查询匹配的整个文档

您希望只返回文档的一部分,但无法指定在2.0中只返回匹配的数组元素

从版本2.2开始(下一个生产版本目前作为不稳定开发版本2.1提供),您将能够使用聚合框架获取本例中所需的内容

2.2还支持-请注意,这将最多返回一个匹配的数组元素

使用聚合框架,您可以执行以下操作:

db.myCollection.aggregate( [
     {$match : { my_entries : { $elemMatch : { e_posted : "2010-06-01", e_name : "f2" } } } },
     {$unwind : "$my_entries"},
     {$match : { my_entries : { e_posted : "2010-06-01", e_name : "f2" } } }
] )

这将返回与所有my_entries数组中的匹配条目数量相同的文档。如果要将它们分组,则需要在管道末尾添加一个
{$group:}
条目。

在mongodb 2.0.4版中不使用mapreduce的情况下,我是否可以使用任何其他技巧解决此问题。您可以在应用程序端执行此操作--匹配文档,然后在检索后取出所需内容。您只能通过$slice运算符获取数组的子集,但这需要知道数组元素的位置。在mongodb的2.2版中,这似乎不是此功能,是否有任何相关信息可以解决我的问题。在2.2版中,您可以在投影中使用$elemMatch(第二个参数传递给'find',但它最多返回一个匹配的数组元素(第一个)。如果要使用agg框架,则需要使用形式为$match:\u u,$unwind:\u,$match:\u,$group:___