0

How do I query in mongoDB using the mongoDB java driver for a numberLong field?

I tried this according to this SO post: Java Mongodb numberlong query but it does not work.

Query query= new Query();
query.addCriteria(Criteria.where("time").is("NumberLong("+article.getDate()+")"));

I also tried this where article.getDate() has a return type of Long and it does not work:

    query.addCriteria(Criteria.where("time").is(article.getDate()));

There is no new NumberLong object within the java driver to use.

https://docs.mongodb.org/manual/core/shell-types/ suggest that one uses NumberLong() wrapper but it is only for the javascript shell, not for java.

2 Answers 2

0
    MongoClient client = new MongoClient();
    MongoDatabase mongoDb = client.getDatabase("test");
    MongoCollection<Document> mongoCollection = mongoDb
            .getCollection("numberFormatTest");

    mongoCollection.drop();

    Document smith = new Document("name", "Smith").append("age", 30)
            .append("profession", "Programmer")
            .append("phoneNo", "9848022338");

    Document jones = new Document("name", "Jones").append("age", 30)
            .append("profession", "Hacker")
            .append("phoneNo", "9000000000000");

    printJson(smith);
    printJson(jones);
    // mongoCollection.insertMany(asList(smith,jones));

    System.out.println("Phone number: "
            + Long.valueOf(smith.getString("phoneNo")).longValue());

The above piece of code might work for you. At the moment, I tried with find but it will work for updates as well.

Even in the above link shared by you,NumberLong wrapper saves the field value in string datatype not as a long datatype. The below statement proves it.

"The NumberLong() wrapper accepts the long as a string:"

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

Comments

0

I think it was just my oversight in this case. The query here actually works:

 query.addCriteria(Criteria.where("time").is(article.getDate()));

I had called my object field as "date" instead of "time", which met it did not get picked up when i queried. Changing it as follows made it work properly.

 query.addCriteria(Criteria.where("date").is(article.getDate()));

Comments

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.