简体   繁体   English

Java MongoDB:使用numberLong字段进行查询

[英]Java MongoDB: querying with numberLong field

How do I query in mongoDB using the mongoDB java driver for a numberLong field? 如何使用mongoDB Java驱动程序在mongoDB中查询numberLong字段?

I tried this according to this SO post: Java Mongodb numberlong query but it does not work. 我根据这篇SO帖子对此进行了尝试: Java Mongodb numberlong查询,但是它不起作用。

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: 我还尝试了以下方法,其中article.getDate()的返回类型为Long,但它不起作用:

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

There is no new NumberLong object within the java driver to use. Java驱动程序中没有new NumberLong对象可使用。

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. https://docs.mongodb.org/manual/core/shell-types/建议使用NumberLong()包装器,但这仅适用于javascript shell,不适用于Java。

    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. 目前,我尝试使用find,但是它也可以用于更新。

Even in the above link shared by you,NumberLong wrapper saves the field value in string datatype not as a long datatype. 即使在您共享的上述链接中,NumberLong包装器也将字段值保存为字符串数据类型,而不是长数据类型。 The below statement proves it. 以下陈述证明了这一点。

"The NumberLong() wrapper accepts the long as a string:" “ NumberLong()包装器将long作为字符串接受:”

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()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM