用Java编写mongoDB"查询和更新"。
mongoDB Collection(名称:reduce(结果(map-reduce result(如下所示:
值字段:
{ "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."]
}
}
试图找到所有推文包含"单词"的User_Name,我可以使用正则表达式指定该单词。
为了实现这一目标,我尝试了聚合输出,它适用于简单情况。但是这个结构,我无法通过它。
法典:
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);
这里的"德克萨斯"是我试图找到的词,我希望输出[Mitchamoreagent].
但是输出始终是异常 noRowsReturns。
按如下方式构造$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);