0

Using MongoDB shell I use:

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)? I try with:

At first I create a DBObject for $match stage:

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

Then I create a BasicDBList:

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

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

And this is the $project stage:

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.

I get an error: "errmsg" : "invalid operator '$contribs'" , "code" : 15999

1 Answer 1

1

You created a DBObject when you were meant to create a List. Also DBList has been deprecated for a while now. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I was stuck for two hours. I know in Java Driver 3.0 there are new features, but I started my project with 2.14.1. Then I'm going to pass to Java Driver 3.0+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.