0

Hy,

I need some help translating the following MongoDB Query into MongoDB Java driver query.

Please be advised that the query works.

db.days.aggregate([
    { $match: { 'day' : 'March_1'}},
    { $project: {
        _id : 0,
        day: 1,
        events: {$filter: {
            input: '$events',
            as: 'event',
            cond: {$eq: ['$$event.year', '2002']}
        }}
    }}
])

My try is this, but it failed and I need your help.

Document query = new Document("$match", new Document("day", day)).
    append("$project", new Document("_id", 0).
            append("day", 1).
            append("events", new Document("$filter", new Document(
                    "input", "$" + category).
                    append("as", "event").
                    append("cond", new Document("$eq", Arrays.asList("$$event.year", year))))));

The error that I am getting is

"{ "ok" : 0.0, "errmsg" : "A pipeline stage specification object must contain exactly one field.", "code" : 16435 }"

Thank you very much!

3
  • What error are you getting? Commented Apr 5, 2016 at 10:29
  • Please see edit. Thank you! Commented Apr 5, 2016 at 10:32
  • The problem that I think it is is that I build a document instead of an array. But I could not find anything that build an array using Documents. Commented Apr 5, 2016 at 10:38

1 Answer 1

5

Don't place the $match and $project in the same object, use a list

AggregateIterable<Document> iterable = collection.aggregate(
  asList(
    new Document("$match", new Document("day", day)),
    new Document("$project", 
        new Document("_id", "0")
            .append("day", 1)
            .append(
                "events", 
                new Document(
                    "$filter",
                    new Document("input", "$events")
                        .append("as", "event")
                        .append(
                            "cond", 
                            new Document("eq", Arrays.asList("$$event.year", year))
                        )
                )
            )
    )
   )
)   
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I just started using MongoDB a few days ago and I am going to kill myself with Java...

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.