Mongodb拉出部分文件

时间:2014-05-27 13:11:00

标签: mongodb mongodb-query

我的文档中有另一个嵌套文档,表示更改(日志记录)。每个更改文档都有时间戳,字段,旧值和新值。基本上你可以看到这个文档会增长很多,我真的不希望得到所有的变化,但只是最近的变化。

我想要做的是进行查询,只获得那些更改,这些更改介于两个时间戳之间。我对文档中的任何其他信息不感兴趣,所以我不想拉它,只是最近的更改。

    {
          .......
        "adwordsChanges":[
          {
             "timestamp":NumberLong("1400162491325"),
             "field":"syncState",
             "old":null,
             "new":"OK"
          },
          {
             "timestamp":NumberLong("1400162491325"),
             "field":"keywordId",
             "old":null,
             "new":NumberLong("23918779329")
          },
          {
             "timestamp":NumberLong("1400162491325"),
             "field":"adGroupId",
             "old":null,
             "new":NumberLong("16972286472")
          }
       ]
    }

这就是我尝试过的!

db.keywords.find(
{
    $and :[{"_id" : ObjectId("5374c7a7ac58b0d3b5e970fa")}, {"adwordsChanges.field" : "keywordId"}, {"adwordsChanges.timestamp" : {$gte:NumberLong("11111111"), $lte:NumberLong(99999999999999) }}]
})

运行Andrei的查询我收到编译错误:

assert: command failed: {
        "errmsg" : "exception: The top-level _id field is the only field currently supported for exclusion",
        "code" : 16406,
        "ok" : 0
} : aggregate failed
Error: command failed: {
        "errmsg" : "exception: The top-level _id field is the only field currently supported for exclusion",
        "code" : 16406,
        "ok" : 0
} : aggregate failed
    at Error (<anonymous>)
    at doassert (src/mongo/shell/assert.js:11:14)
    at Function.assert.commandWorked (src/mongo/shell/assert.js:244:5)
    at DBCollection.aggregate (src/mongo/shell/collection.js:1149:12)
    at (shell):1:13
2014-05-27T15:23:54.945+0100 Error: command failed: {
        "errmsg" : "exception: The top-level _id field is the only field currently supported for exclusion",
        "code" : 16406,
        "ok" : 0

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用聚合框架来过滤子文档,如下所示:

db.keywords.aggregate({$unwind:"$adwordsChanges"},
                      {$match:{"adwordsChanges.timestamp" : 
                                      {$gte:1400162491325, $lte:23918779329},
                               "adwordsChanges.field" : "keywordId"}},
                      {$project:{_id:0,
                                 timestamp:"$adwordsChanges.timestamp",   
                                 field:"$adwordsChanges.field", 
                                 old:"$adwordsChanges.old",   
                                 new:"$adwordsChanges.new"   
                                 }});

项目与群组之间差异的解释

最初我认为应该返回原始文档并使用group来恢复原始文档结构,即在这种情况下groupunwind的操作相反。澄清之后,很明显只需要子文档,然后我用group替换project操作,以便将子文档投影到根级别。