【问题标题】:MongoDB: Querying for subdocuments: JavaMongoDB:查询子文档:Java
【发布时间】:2014-12-16 23:11:44
【问题描述】:

用 Java 编写一个 mongoDB“查询和更新”。

mongoDB 集合(名称:reduce)结果(map-reduce 结果)如下所示:

值域:

{ "value" : 

    { 
        "User_Name" : "Mitchamoreagent",
        "tweets" : ["RT    Perspectives:
        Texas Insurer of Last Resort Charts Course Through Reform Law", "RT  Texas sale
        s tax-free weekend set for Aug. 19-21", "RT  The New Normal: Billion-Dollar", "R
        T  Austin Water is responding to a 12-inch water main leak at Burnet Rd. and And
        erson Lane in North Austin."] 
    }
}

试图找到所有推文中包含“单词”的用户名,我可以使用正则表达式来指定。

为了实现这一点,我尝试了 AggregationOutput,它适用于简单的情况。但是这个结构,我是打不通的。

代码:

 DBObject match = new BasicDBObject("$match",new BasicDBObject("value",new    BasicDBObject("tweets", new BasicDBObject("$regex",".*Texas.*"))));
 DBObject fields = new BasicDBObject("_id", 0); 
 DBObject nest = new BasicDBObject("value", new BasicDBObject("User_ID", 1));
 fields.put("value", 1);
 DBObject project = new BasicDBObject("$project", fields );
 AggregationOutput output = tweets.aggregate( match, project);

这里 'Texas' 是我要查找的单词,我希望输出 [Mitchamoreagent].

但输出始终是noRowsReturned异常。

【问题讨论】:

    标签: java regex mongodb mapreduce aggregation-framework


    【解决方案1】:

    您需要如下构建您的$match 阶段操作:

     DBObject regex = new BasicDBObject("$regex","Texas");
     DBObject condition = new BasicDBObject("value.tweets",regex);
     DBObject match = new BasicDBObject("$match",condition);
    

    在您的问题中生成的相应 mongodb 查询将是:

    {$match:{"value":{"tweets":{$regex:"Texas"}}}}
    

    实际上应该形成为:

    {$match:{"value.tweets":{$regex:"Texas"}}}
    

    项目阶段应构建如下:

    当您需要将嵌套字段的值投影为顶级字段时,在本例中为 User_name,您需要使用别名进行投影,在本例中别名为 user_name

     DBObject fields = new BasicDBObject("_id", 0); 
     fields.put("user_name", "$value.User_Name"); // project the user_name for each record.
    

    执行管道:

     DBObject project = new BasicDBObject("$project", fields );
     AggregationOutput output = tweets.aggregate( match, project);
    

    【讨论】:

    • 如果我只想要结果中的“用户名”,您能否告诉我“项目”应该是什么样子。由于我使用的是 AggregationOutput output = tweets.aggregate(match, project);
    • 你能解释一下 fields.put() 中的这个“$value.User_Name”
    • col.aggregate(匹配,项目); stmt中的'col',应该是整个集合的名字吧?或者应该是推文,因为我们正在将单词与推文匹配。尽管我可以在 mongoDB shell 中通过查询看到值,但它仍然给我一个空白的 o/p。
    • 这是一个错字。应该是推文。它是 DBCollection 变量引用。
    • 成功了。非常感谢!!我使用了 reduce.aggregate(match, project);这是我在问题中使用的集合名称。
    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多