-1

This is really hard. I want to find the select nodes.index where radio.mac_address="00:06:5A:03:2E:5B". how can I get this query in MongoDB using java? My mongodb is as following.

enter image description here

I tried so many queries. one of them is as following

BasicDBObject query = new BasicDBObject("nodes.radios.mac_address", "mac_address value";
BasicDBObject fields = new BasicDBObject("nodes.$", 1);
DBCursor cursor = node_info.find(query, fields);

Updated First on got solved

How can i also write update query like update rssiLocal="90" where mac_address="00:06:5A:03:2E:5B".

Hitesh Vaghani
  • 1,342
  • 12
  • 31
  • 1
    Can you check this query work with your collection `db.collectionName.find({"nodes":{"$elemMatch":{"radios":{"$elemMatch":{"mac_address":"00:06:5A:03:2E:5B"}}}}},{"nodes.$.index":1})` – Neo-coder Apr 14 '15 at 10:56
  • Nope giving me empty document. – Hitesh Vaghani Apr 14 '15 at 11:09
  • ok so this case you should use mongo aggregation http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/ – Neo-coder Apr 14 '15 at 11:12
  • @yogesh That query works fine. Its giving me whole document which contains the mac_address than just index. – Hitesh Vaghani Apr 14 '15 at 13:23
  • how can i update `radio_index where mac_address="some value"`. – Hitesh Vaghani Apr 15 '15 at 05:59
  • multi level nested update not possible using mongo query, you should used java programming code to update. For more help check this link http://stackoverflow.com/questions/29634150/updating-nested-array-inside-array-mongodb – Neo-coder Apr 15 '15 at 07:33

1 Answers1

-1

In my application I use following method. It finds an object according to given id parses it via Gson and saves it to corresponding object.

 public MyEntity getValue(String id) {
        DB db = SessionManager.getInstance().db;
        DBCollection collection = db.getCollection("myCollection");
        BasicDBObject query = new BasicDBObject("_id", id);
        Object object = new Object();
        boolean found = false;

        DBCursor cursor = collection.find(query);
        try {
            while (cursor.hasNext()) {
                found = true;
                String str = (cursor.next().toString());
                Gson gson = new Gson();

                object = gson.fromJson(str, MyEntity.class);

            }
        } finally {
            cursor.close();
        }
        if (!found)
            return new MyEntity();
        MyEntity myEntity = null;
        myEntity = (MyEntity) object;
        return myEntity;
    }
Martin Dvoracek
  • 1,714
  • 6
  • 27
  • 55