0

I am using MongoDB 3.2 with Java. I read the documentation and it says to use org.bson.BsonDocument since other options like BSONObject and Document are deprecated. Now, I have query similar to:

db.schools.find({ zipcode: "63109" },
    { students: { $elemMatch: { school: 102 } } } )

I am wondering: how can I write this query in Java?

Note: Here we have two documents inside the find function, while it accepts only single Bson Document or multiple Bson Element(s).

Any help would be appreciated.

1 Answer 1

1

Try to use one document for the condition, like db.schools.find({ zipcode: "000000", students: { $elemMatch: { school: 102 }});

EDIT:

So, you are using Projection. In java mongodb driver 3.3 there are: public DBCursor find(DBObject query, DBObject projection). I think you should update your java mongodb driver.

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

7 Comments

I tried but it returns all the elements of the array which is something I don't want.
Do you want to query all schools that have 63109 zipcode and in the 'students' array of subdocuments there is any element with 'school' equals 102?
In my case, there is only one school with zipcode as 63109, which has multiple subdocuments in students array out of which i just want one with school as 102.
In MongoDB you can't query sudocuments. You can query documents only. If you want to query students, you shold move them to their own collection, or filter query results in JAVA
But above query I mentioned is working fine with console, where it gives me the only subdocument I want. So I just want to convert console query to 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.