Amriteya
Amriteya

Reputation: 1172

Mongodb query for nested document in java

I am new to Mongodb. I have the following dataset in mongodb.

{
"_id": {
    "$oid": "563644f44b17ca12886440a9"
},
"data": [
    {
        "uid": 1,
        "character": " ",
        "unicode": 32,
        "color": -7309587
    },
    {
        "uid": 2,
        "character": "!",
        "unicode": 33,
        "color": -8911704
    },
    {
        "uid": 3,
        "character": "\"",
        "unicode": 34,
        "color": -1778539
    }

I am trying to retrieve the color from this field using the _id and character. I am not able to execute the query.

This is what I tried.

DBObject clause1 = new BasicDBObject("_id",new ObjectId(KEY1));  
                DBObject clause2 = new BasicDBObject("data.character",text[i]);    
                BasicDBList or = new BasicDBList();
                or.add(clause1);
                or.add(clause2);
                DBObject query = new BasicDBObject("$and", or);

Also I am having a lot of issues in finding ways to query in mongodb-java for the 3.0.0+ api. Could someone please help?

Upvotes: 1

Views: 3118

Answers (2)

Dev
Dev

Reputation: 13753

    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    MongoDatabase db = mongoClient.getDatabase("testDB");
    AggregateIterable<Document> iterable = db.getCollection("testCollection").aggregate(
            asList(new Document("$unwind", "$data"), new Document("$match", (new Document("_id", new ObjectId(
                    "5636f106b2acf98ecb033b98")).append("data.character", " "))), new Document("$project",
                    new Document("data.color", 1).append("_id", 0))));

    iterable.forEach(new Block<Document>()
    {
        @Override
        public void apply(final Document document)
        {
            System.out.println(document.toJson());
        }
    });

For more details check MongoDB Documentation.

Upvotes: 1

Clement Amarnath
Clement Amarnath

Reputation: 5466

A simple solution

In your document, oid is an unique key for each document and hence your query should be like this

  DBObject query = new BasicDBObject("_id.oid", KEY1);
  // Query with value - DBObject query = new BasicDBObject("_id.oid","563644f44b17ca12886440a9");

  Assign this to a cursor as shown below
  DBCollection coll = db.getCollection("mycollection");
  DBCursor cursor = coll.find(query);
  Iterate the collection and retrieve your desired value.

Upvotes: 0

Related Questions