Ratik
Ratik

Reputation: 29

How to extract only one value from mongoDB?

LIKE I HAVE THREE FIELD 'TO','FROM' AND 'MESSAGE', I just want to display content of message field where I have given some clause in to and from. Document{{_id=59c7d57c674cd5673c304936, to=9915103230, from=9915103229, date=24/12/2017, message=HELLO WORLD}}

I JUST WANT TO RETRIEVE "HELLO WORLD", not the whole document.

Like I just want, String message=?????---> I need some method here so the Variable of String type gets the value Hello World.

Projection method is not working for me.

I am using JDBC MongoDB 3.5 Driver.

Upvotes: 0

Views: 883

Answers (2)

Buzz Moschetti
Buzz Moschetti

Reputation: 7588

Here's a functioning prog. Compile against the 3.5 drivers.

        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase( "testX" );
        MongoCollection<BsonDocument> coll = db.getCollection("foo", BsonDocument.class);
        coll.drop();

        {
            BsonDocument doc = new BsonDocument();
            doc.put("from", new BsonInt32(23343223));
            doc.put("to", new BsonInt32(23343223));
            doc.put("msg", new BsonString("hello"));
            coll.insertOne(doc);

            doc.remove("_id");
            doc.put("from", new BsonInt32(8889));
            doc.put("to", new BsonInt32(99999));
            doc.put("msg", new BsonString("goodbye"));
            coll.insertOne(doc);
        }

        {
            BsonDocument query = new BsonDocument("from", new BsonInt32(8889));
            BsonDocument proj = new BsonDocument("msg", new BsonInt32(1));
            proj.put("_id",new BsonInt32(0));

            BsonDocument d2 = coll.find(query).projection(proj).first();
            System.out.println(d2);

            String s2 = coll.find(query).projection(proj).first().getString("msg").getValue();
            System.out.println(s2);
        }

Upvotes: 0

Buzz Moschetti
Buzz Moschetti

Reputation: 7588

Use projection, the second optional argument to find(). For context, this gives you the whole document:

db.yourCollection.find({to:9915103230,from:9915103229});

This gives you only message from the results. Just name the field and set it to 1:

db.yourCollection.find({to:9915103230,from:9915103229},{message:1};

You can specify more than one thing to return:

db.yourCollection.find({to:9915103230,from:9915103229},{message:1, to:1};

Upvotes: 1

Related Questions