运行 使用 Java 驱动程序的聚合 - MongoDB

Run an aggregation using Java Driver - MongoDB

使用 MongoDB shell 我使用:

db.bios.aggregate(
[
{$match:{"contribs.0.name":{"$exists":1}}}, 
{$project: {contribs:{$arrayElemAt:["$contribs",0]}}}
]
)

如何使用 Java 驱动程序 (2.14.1) 进行相同的查询? 我尝试:

首先我为 $match 阶段创建了一个 DBObject:

DBObject match = new BasicDBObject("$match",new BasicDBObject("contribs.0.name",
                 new BasicDBObject("$exists",1)));

然后我创建一个 BasicDBList:

BasicDBObject obj = new BasicDBObject("$contribs",0);

BasicDBList arrayElemAt = new BasicDBList();
arrayElemAt.add(obj);

这是 $project 阶段:

DBObject project1 = new BasicDBObject("$project", new BasicDBObject("contribs",
                    new BasicDBObject("$arrayElemAt",arrayElemAt)));

最后我创建了聚合管道:

List<DBObject> list = new ArrayList<>();
list.add(match);
list.add(project1);

AggregationOutput output = this.coll.aggregate(list);

$Match 阶段有效,但 $project 无效。

我得到一个错误:"errmsg" : "invalid operator '$contribs'" , "code" : 15999

当您打算创建一个 List 时,您创建了一个 DBObject。另外 DBList 已经弃用一段时间了。习惯使用标准列表符号:

    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);

另请注意,在现代驱动程序中,您确实应该使用 Document 代替所有 DBObject 类型。