简体   繁体   中英

MongoDb Java get single document by custom _id

Im having a bit of trouble getting a single document by id (i inserted my own id's).

I have had a look at the driver documentation but i cant find anything that tells me how i can get a single document.

My collection looks like so

{ "_id" : NumberLong(1), "currency_pair" : "GBP/USD", "date" : "2009-05-01 00:00:00", "sell" : "1.47993", "buy" : "1.48076", "spread" : 0.0008300000000001084 }
{ "_id" : NumberLong(2), "currency_pair" : "GBP/USD", "date" : "2009-05-01 00:00:00", "sell" : "1.48023", "buy" : "1.48076", "spread" : 0.0005300000000001415 }
{ "_id" : NumberLong(3), "currency_pair" : "GBP/USD", "date" : "2009-05-01 00:00:01", "sell" : "1.48023", "buy" : "1.48077", "spread" : 0.0005399999999999849 }

My current query looks like this.

        if (!Main.REMOTE) {
            server = "localhost";
        }

        MongoClient mongoClient = new MongoClient( server );
        MongoDatabase db = mongoClient.getDatabase("rates");
        MongoCollection<Document> coll = db.getCollection(tableName);

        BasicDBObject query=new BasicDBObject("_id", 2);
        coll.find(query);

尝试:

BasicDBObject query=new BasicDBObject("_id", NumberLong(2));

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