0

I have the following query in MongoDB:

db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'},
{ _id:0, objectData:0, lastModified :0, productCode:0})

Also, I would like to calculate number of records, that is possible in Mongo shell by using count

db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'},
{ _id:0, objectData:0, lastModified :0, productCode:0}).count()

How to write the analogous queries in Java using Java MongoDB driver, version 3?

3
  • Have you checked this out? mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/… Commented Aug 5, 2015 at 22:22
  • I could not find how to use regex in Java find, in this document either Commented Aug 5, 2015 at 22:26
  • 1
    Okay, I haven't dug very deep into that doc. But from using the C# driver, there is something left to be desired. Commented Aug 5, 2015 at 22:37

1 Answer 1

2

Constructing queries is really just creating BSON document representation, which is basically just the same interface as standard HashMap or List interfaces as appropriate:

    Document query = new Document("objectKey",new Document( "$regex","Bos"))
        .append("cacheVersionString","08/03/15_11:05:09");

    Document projection = new Document("_id",0)
        .append("objectData",0)
        .append("lastModified",0)
        .append("productCode",0);

    MongoCursor<Document> cursor = collection.find(query).projection(projection).iterator();

Where that is basically identical to how you are structuring queries in the MongoDB shell.

Alternately you can use builder interfaces if that seems more logical to you:

    QueryBuilder builder = QueryBuilder.start();

    builder.and("objectKey").regex(Pattern.compile("box"));
    builder.and("cache_version_string").is("08/03/15_11:05:09");

    BasicDBObject query = (BasicDBObject)builder.get();

    Bson projection = Projections.exclude(
            "_id",
            "obectdata",
            "lasModified",
            "productCode"
    );

    MongoCursor<Document> cursor = collection.find(query).projection(projection).iterator();

    while (cursor.hasNext()) {
        Document doc = cursor.next();
        System.out.println(doc.toJson());
    }

Both forms essentially contruct the BSON for both the "query" and "projection" components and issue them as arguments to the .find() method. There are also class type definitions if that suits you as well.

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

1 Comment

thank you. I also added the question about count, do you have any idea?

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.