Li'
Li'

Reputation: 3183

How to identify document in MongoDB in Java

I am wondering if MongoDB provide some good schema for identifying documents in the database. Suppose I have initialized a database like this:

public static void main(String[] args) {

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");

DBCollection coll = db.getCollection("mycollection");

BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
}

Now How can I get the "document" inserted in the database? I already know a key/value pair query can locate the document, like:

BasicDBObject query = new BasicDBObject();
query.put("name", "Mike");
DBObject dbObj = coll.findOne(query);

Is there another way other than this kind of key/value pair query to identify the document?

If you want to identify a collection, you can do it by match the collection name:

DBCollection coll = db.getCollection("mycollection");

I hope there is something like this to identify the document. Any suggestion?

Upvotes: 0

Views: 258

Answers (1)

Rob Moore
Rob Moore

Reputation: 3383

If you look in the document object after the coll.insert(document); you will find that a _id field was added by the driver. You can use this field/value to query for the exact document since MongoDB enforces there must be an _id field and it must be unique.

Putting this all together:

public static void main(String[] args) {

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("testdb");

    DBCollection coll = db.getCollection("mycollection");

    BasicDBObject document = new BasicDBObject();
    document.put("name", "Mike");
    document.put("age", 25);
    coll.insert(document);

    System.out.println(document.get("_id"));

    BasicDBObject query = new BasicDBObject();
    query.put("_id" , document.get("_id"));

    DBObject retrieved = collection.findOne(query);
    System.out.println(retrieved);
}

Upvotes: 1

Related Questions