1

Suppose we have the following documents in a MongoDB collection:

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"circle",
         "color":"red"
      }
   ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"black"
      },
      {  
         "shape":"circle",
         "color":"green"
      }
   ]
}

And the MongoDB query is

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

Can someone tell me how to write it in Java?

I am using:

List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));

BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);

DBCursor cursor = table.find(parameters1,obj2).limit(500);

and I am not getting anything.

1
  • Don't use list. Just create BasicDBObject one for each query and projection and pass it to find. Something like BasicDBObject obj = new BasicDBObject("shapes.color", "red"); BasicDBObject obj1 = new BasicDBObject("shapes.$", "1"); DBCursor cursor = table.find(obj,obj1).limit(500); Commented Mar 21, 2018 at 23:53

1 Answer 1

3

The syntax of the Mongo Shell find function is:

db.collection.find(query, projection)

query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).

projection document Optional. Specifies the fields to return in the documents that match the query filter.

When translating this for execution by the Mongo Java driver you need to construct separate BasicDBObject instances for;

  • the query
  • the projection

Here's an example:

MongoCollection<Document> table = ...;

// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");

// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);

FindIterable<Document> documents = table
    // assign the query
    .find(query)
    // assign the projection
    .projection(projection);

System.out.println(documents.first().toJson());

Given the sample documents included in your question the above code will print out:

{
  "shapes": [
    {
      "shape": "circle",
      "color": "red"
    }
  ]
}

This is identical to the output from db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});.

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.