Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.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
Spring 查询文档的子数组_Spring_Mongodb - Fatal编程技术网

Spring 查询文档的子数组

Spring 查询文档的子数组,spring,mongodb,Spring,Mongodb,我有一个帖子数据库,其对象包含评论数组 { "_id" : "g-6892440-S-5949476530307559428", "title" : "something", "comments" : [] } { "_id" : "g-6892440-S-5946310723729645572", "title" : "something again", "comments" : [ { "_id" :

我有一个帖子数据库,其对象包含评论数组

{
    "_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的评论。我找到了这个教程,里面有一些类似的东西。我的问题是:

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框架中实现查询。非常感谢。

使用这个:

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
对于聚合而言,春天可能是:从


谢谢你的工作。但我不明白有什么评论。$确切地说,为什么官方教程中没有写这方面的内容。Thank$是位置操作,当您查询注释时。text:aaa,mongo将发现注释的第二个数组成员的文本为aaa'。mongo将$转换为1作为索引,它将返回注释。1意味着从数组中选择1的索引,其他注释的索引可能会有所不同。这是一个很好的更新参考,但您可以在find query Ok中获得相同的行为,谢谢。现在,我发现命令db.posts.find{comments.text:aaa},{u id:0,comments.$:1,comments.{u id:1,comments.text:1}不仅返回{u id和文本,还返回注释的所有字段。我怎样才能只获得两个字段。谢谢
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);