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.

Community
  • 1
  • 1
Simon
  • 19,658
  • 27
  • 149
  • 217

2 Answers2

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:"

harshavmb
  • 3,404
  • 3
  • 21
  • 55
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()));
Simon
  • 19,658
  • 27
  • 149
  • 217