2014-03-27 27 views
1

我的MongoDB的集合是这样的:MongoDB的查询只在内部文件

{ 
     "_id" : ObjectId("5333bf6b2988dc2230c9c924"), 
     "name" : "Mongo2", 
     "notes" : [ 
       { 
        "title" : "mongodb1", 
        "content" : "mongo content1" 
       }, 
       { 
        "title" : "replicaset1", 
        "content" : "replca content1" 
       } 
     ] 
    } 
    { 
     "_id" : ObjectId("5333fd402988dc2230c9c925"), 
     "name" : "Mongo2", 
     "notes" : [ 
       { 
        "title" : "mongodb2", 
        "content" : "mongo content2" 
       }, 
        { 
          "title" : "replicaset1", 
          "content" : "replca content1" 
        }, 
        { 
          "title" : "mongodb2", 
          "content" : "mongo content3" 
        } 
      ] 
    } 

我想查询只显示有标题为“mongodb2”,但不希望完整的文档说明。 我使用下面的查询:

> db.test.find({ 'notes.title': 'mongodb2' }, {'notes.$': 1}).pretty() 
    { 
      "_id" : ObjectId("5333fd402988dc2230c9c925"), 
      "notes" : [ 
        { 
          "title" : "mongodb2", 
          "content" : "mongo bakwas2" 
        } 
      ] 
    } 

我期待它返回都指出,有标题为“mongodb2”。 当我们查询文档中的文档时,mongo是否只返回第一个文档?

+0

可能重复的[MongoDB只提取数组中的选定项](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array) – WiredPrairie

+0

此问题已被已经在StackOverflow上多次询问和回答。看看上面的链接和这个:例如http://stackoverflow.com/questions/5562485/get-particular-element-from-mongodb-array。 – WiredPrairie

+0

我觉得难以遵循这些问题,因为它们来自聚合框架不存在的时间。对这些问题之一的接受答案甚至是使用map/reduce,这几乎肯定不是OP所要的,因为M/R不适合临时查询。 – mnemosyn

回答

1

positional $运营商只能返回它找到的匹配索引第一个匹配索引。

使用aggregate

db.test.aggregate([ 

    // Match only the valid documents to narrow down 
    { "$match": { "notes.title": "mongodb2" } }, 

    // Unwind the array 
    { "$unwind": "$notes" }, 

    // Filter just the array 
    { "$match": { "notes.title": "mongodb2" } }, 

    // Reform via group 
    { "$group": { 
     "_id": "$_id", 
     "name": { "$first": "$name" }, 
     "notes": { "$push": "$notes" } 
    }}  
]) 

所以,你可以用它来 “过滤器” 从特定的阵列文档。

1

$总是指第一个匹配,$elemMatch投影算子也是如此。

我觉得你有三种选择:

  1. 单独的音符所以每个为自己的
  2. 接受通过网络和过滤器的客户端发送更多数据
  3. 使用聚合管道的文件($match$project

我可能会选择选项1,但你可能有你的数据模型的原因。

+0

我没有将笔记作为一个单独的文档分开,因为所有笔记都有很少的重复常见值。如果我要在选项2和3之间进行选择,则不确定哪一个具有更好的性能。还需要考虑使用Spring数据存储库的实现。 – jay