1

My mongo collections contains following documents

{

"syslog": [
    {
        "alertId": "N/A",
        "time": "06:46:57",
        "device": "10.10.20.1"
    },
    {
        "alertId": "N/A",
        "time": "06:47:30",
        "device": "10.10.20.2"
    }
]
}

now I want to read only values of given device.

Suppose if I set device="10.10.20.2" it will shows only "alertId": "N/A", "time": "06:47:30", "device": "10.10.20.2" for this I write java code as below

BasicDBObject criteria = new BasicDBObject();                                       

criteria.put("syslog.device","10.10.20.2");
DBCursor cur = coll.find(criteria);
while(cur.hasNext() && !isStopped()) {
    String json = cur.next().toString(); 
}//end of while

When I print json it shows me whole json values. How I should find only selected values of given device?

2
  • What do you mean with When I print json it shows me whole json values ? Commented Jan 29, 2014 at 12:43
  • dont print the whole JSON, pick the fields you want before you convert it to string Commented Jan 29, 2014 at 12:46

1 Answer 1

3

You should use $elemMatch operator to project array fields. You should update your query as follows :

db.collection.find({"syslog.device" : "10.10.20.2"},{syslog : {$elemMatch : {device : "10.10.20.2"}}})

In Java :

BasicDBObject criteria = new BasicDBObject();                                       
criteria.put("syslog.device","10.10.20.2");

BasicDBObject elemMatchObj = new BasicDBObject();
elemMatchObj.put("$elemMatch", new BasicDBObject("device", "10.10.20.2"));

DBCursor cur = coll.find(criteria, new BasicDBObject("syslog", elemMatchObj));
while(cur.hasNext() && !isStopped()) {
    String json = cur.next().toString(); 
}//end of while
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.