查询文档子数组

时间:2014-12-28 17:16:54

标签: spring mongodb

我有一个帖子数据库,其对象包含注释数组。

{
    "_id" : "g-6892440-S-5949476530307559428",
    "title" : "something",
    "comments" : []
}
{
    "_id" : "g-6892440-S-5946310723729645572",
    "title" : "something again",
    "comments" : [ 
        {
            "_id" : "11",
            "text" : "aaa",            
        }, 
        {
            "_id" : "22",
            "text" : "bbb",            
        }
    ]
}

我想得到的评论文字是“aaa”。我找到了这个教程http://docs.mongodb.org/manual/core/index-multikey/,其中有类似的东西。我的疑问是:

db.posts.find({"comments.text": "aaa" }, {"_id" : 0 , "comments._id" : 1, "comments.text" : 1 })

返回

{
    "comments" : [ 
        {
            "_id" : "g-6892440-S-5946310723729645572-5946311678785249280",
            "text" : "aaa"
        }, 
        {
            "_id" : "g-6892440-S-5946310723729645572-5946311735404158977",
            "text" : "bbb"
        }
    ]
}

但我只想要评论文字等于“aaa”。我还尝试按命令执行索引:

db.posts.ensureIndex( { "comments.text": 1 } )

但它没有帮助。

第二个问题是如何在Spring MongoDB框架中实现查询。非常感谢。

1 个答案:

答案 0 :(得分:0)

使用它:

db.posts.find({"comments.text": "aaa" }, {"_id" : 0 , "comments.$" : 1, "comments._id" : 1, "comments.text" : 1 })

当然还有另一种方法可以通过聚合来实现这一点:

db.posts.aggregate(
   { $project : { comments : "$comments" , _id : 0}},
   { $unwind : "$comments"}, 
   { $match : {"comments.text": "aaa" }}
).result

对于聚合,弹簧可以是:(来自https://blog.42.nl/articles/aggregations-mongodb-spring-data/

DBCollection posts...
DBObject match = new BasicDBObject("$match", new BasicDBObject("comments.text", "aaa"));
DBObject unwind = new BasicDBObject("$unwind", "$comments");
DBObject fields = new BasicDBObject( "_id", 0);
fields.put("comments", "$comments");
DBObject project = new BasicDBObject("$project", fields);
List pipeline = Arrays.asList(project, match, unwind);
AggregationOutput output = posts.aggregate(pipeline);