简体   繁体   中英

How to get Documents less than or greater than some value in mongodb using java

I want to get all the available documents which has the employee id greater than 50 and less than 500 using java.

I have tried like this.

BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("employeeID", new BasicDBObject("$gt", 50).append("$lt", 500));
DBCursor cursor = collection.find(gtQuery);
while(cursor.hasNext()) {
        System.out.println(cursor.next());
};

but I dont get any result from this, even i have documents between that range in the database. Please tell me the reason...

sample format of the document in the collection.

{ "employeeID" : "450", "name" : "AAA" }

Query seems fine, however, I would check the collection it's being executed on (and make sure it's correct).

Also, another way to debug it would be to print the query in the console and execute the same in mongo shell,

eg db.employee.find({employeeID : {$gt : 50, $lt : 500}})

One of the main issues in your collection is that the employeeID is stored as String. If you are 100% sure that all employeeIDs are numerical then I would suggest transforming the field from String to Integer. Try the following code for transforming the employeeID field:

    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        BasicDBObject current_object = (BasicDBObject) cursor.next();

        current_object.update(
                new BasicDBObject().append("_id", current_object.getObjectId("_id"), 
                        new BasicDBObject()
                                .append(
                                        "$set", 
                                        new BasicDBObject("employeeID", Integer.parseInt(current_object.getString("employeeID"))
                                        )
                                )
                )
        );
    }

Then you could use your code for obtaining employees 50 < employeeID < 500.
Make sure that this transformation would not affect your app dramatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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