[英]Run an aggregation using Java Driver - MongoDB
Using MongoDB shell I use: 使用MongoDB shell,我使用:
db.bios.aggregate(
[
{$match:{"contribs.0.name":{"$exists":1}}},
{$project: {contribs:{$arrayElemAt:["$contribs",0]}}}
]
)
How can I make the same query using Java driver ( 2.14.1 )? 如何使用Java驱动程序( 2.14.1 )进行相同的查询? I try with:
我尝试:
At first I create a DBObject for $match
stage: 首先,我为
$match
阶段创建一个DBObject:
DBObject match = new BasicDBObject("$match",new BasicDBObject("contribs.0.name",
new BasicDBObject("$exists",1)));
Then I create a BasicDBList
: 然后我创建一个
BasicDBList
:
BasicDBObject obj = new BasicDBObject("$contribs",0);
BasicDBList arrayElemAt = new BasicDBList();
arrayElemAt.add(obj);
And this is the $project
stage: 这是
$project
阶段:
DBObject project1 = new BasicDBObject("$project", new BasicDBObject("contribs",
new BasicDBObject("$arrayElemAt",arrayElemAt)));
Finally I create the aggregation pipeline: 最后,我创建了聚合管道:
List<DBObject> list = new ArrayList<>();
list.add(match);
list.add(project1);
AggregationOutput output = this.coll.aggregate(list);
$Match
stage works, but $project
does not. $Match
阶段有效,但$project
无效。
I get an error: "errmsg" : "invalid operator '$contribs'" , "code" : 15999
我收到一个错误:
"errmsg" : "invalid operator '$contribs'" , "code" : 15999
You created a DBObject
when you were meant to create a List
. 您本打算创建
List
时创建了一个DBObject
。 Also DBList
has been deprecated for a while now. 此外,
DBList
已经过时了一段时间。 Get used to using standard list notations: 习惯使用标准列表符号:
List<DBObject> pipeline = Arrays.<DBObject>asList(
new BasicDBObject(
"$match",
new BasicDBObject(
"contribs.0", new BasicDBObject("$exists",true)
)
),
new BasicDBObject(
"$project",
new BasicDBObject(
"contribs", new BasicDBObject("$arrayElemAt", Arrays.asList("$contribs",0))
)
)
);
AggregationOutput output = this.coll.aggrgate(pipeline);
Also note that in modern drivers you really should be using Document
in place of all DBObject
types. 还要注意,在现代驱动程序中,您实际上应该使用
Document
代替所有DBObject
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.