How to query for only a certain attribute - java

Suppose I want to query for only a certain attribute of all documents, something like in SQL:
SELECT FIRSTNAME
FROM TABLE1
How can I do it with Mongo and it's Java API?

If you want to get all documents, use an empty object as the first argument. With the second one you only get the field FIRSTNAME.
db.table1.find({}, {'FIRSTNAME': 1});
See the documentation on querying for more details.

In the Java API, you can do it like this. You have to explicitly turn off the _id field, in order to exclude it.
Mongo m = new Mongo();
DB db = m.getDB( "test" );
DBCollection coll = db.getCollection("test");
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
DBCursor curs = coll.find(query, fields);
while(curs.hasNext()) {
DBObject o = curs.next();
System.out.println(o.toString());
}
Output:
{ "Name" : "Wes"}
Update for sort:
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Alex").append("x", "to have a second field"));
coll.insert(new BasicDBObject("Name","Zeus").append("x", "to have a second field"));
BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name",1).append("_id",false);
BasicDBObject orderBy = new BasicDBObject("Name",1);
DBCursor curs = coll.find(query, fields).sort(orderBy);
while(curs.hasNext()) {
DBObject o = curs.next();
System.out.println(o.toString());
}
Gives:
{ "Name" : "Alex"}
{ "Name" : "Wes"}
{ "Name" : "Zeus"}

Related

Retrieving values from basicdblist Mongo

{
DB db = Helper.connectingMonggo();
BasicDBObject query = new BasicDBObject();
query.put("_id", "123");
DBCollection table = new db.getCollection("prodDetail");
DBCursor cursor = table.find(query); --// cursor has only one record (size =1)
while(cursor.hasNext()){
DBObject obj = cursor.next();
List<String> upcs = new ArrayList<>();
BasicDBList list = (BasicDBList) obj.get("prodList"); --//here prodList size also 1 always
DBObject obj1 = (DBObject) list.get(0);
BasicDBList detailsList = (BasicDBList) obj1.get("pDetailsList");
for(Object obj2 : detailsList){
JSONObject obj3 = new JSONObject(JSON.serialize(obj2));
ups.add(obj3.get("upcStatus").toString());
} } }
I am getting the list array with upcStatus but, is it proper way to write?
This is an aggregation query using the MongoDB Java driver v3.12 and MongoDB v4.2. Note the result is returned using a single query and no additional code. This is useful as the query is entirely run on the server and the result is returned to your Java application.
try(MongoClient mongoClient = MongoClients.create()) {
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> coll = database.getCollection("testCollection");
List<Bson> pipeline = Arrays.asList(
Aggregates.match(Filters.eq("_id", 123)),
Aggregates.project(Projections.fields(
Projections.excludeId(),
Projections.computed("upcStatus", Filters.eq("$arrayElemAt",
Arrays.asList("$prodList.pDetailsList.upcStatus", 0L))
)
))
);
Document doc = coll.aggregate(pipeline).first();
System.out.println(doc.toJson()); // prints the array of upcStatus field values
}
The classes used in the code are defined as following classes or in packages: org.bson.Document, org.bson.conversions.Bson, com.mongodb.client.model.* and com.mongodb.client.*.
Also, note the try statement-block opens the connection to the server and closes automatically at the end of the try-block.

Mongo Java query for and/or combination

I need a Java driver mongo query for and/or combination -
for ex -
suppose I have a collection user have 3 field named a, b, c.
Now I have to perform find query like -
user.find({$and :[{"a":"text"},{$or :[{"b":"text"},{"c":"text"}]}]})
This mongo console query give correct result.
How I apply this with JAVA mongo driver.
Please help
Thanks in advance
You can use following query
DBCollection userCollection = db.getCollection("collection");
BasicDBObject orQuery = new BasicDBObject();
List<BasicDBObject> obj1 = new ArrayList<BasicDBObject>();
obj1.add(new BasicDBObject("a", "text"));
obj1.add(new BasicDBObject("b", "text"));
orQuery.put("$or", obj1);
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("c", "text"));
obj.add(orQuery);
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor = userCollection.find(andQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

Finding a single row in MONGO DB driver java using _id field

I am trying to get a single record using the _id field , here is my code
BasicDBObject query = new BasicDBObject("_id","52a6a2cc05e1c80fd5e9295c");
DBCursor cursor = blogTable.find(query);
while (cursor.hasNext())
{
System.out.println("got u");
dataText.setText((cursor.next().get("content:encoded")).toString());
}
I simple don't get any data and I am quite sure the id exist
.please help
I'm guessing that the String you are calling out as "52a6a2cc05e1c80fd5e9295c" is actually an ObjectID in the MongoDB. If this is the case, your lookup is...
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId("52a6a2cc05e1c80fd5e9295c"));
DBObject dbo = blogTable.findOne(query);
if ( dbo != null ) {
System.out.println( "got u " + dbo );
} else {
System.out.println( "not found" );
}
You need to know the types of things in MongoDB.

Convert MongoDB query into Java

I need to convert the following mongo query into java.
db.sample.find( { name:"abc" }, { _id: 0, cities: { $elemMatch: { cityName: "A" }}});
I tried so many ways but I couldn't figure out the correct way.
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
BasicDBObject query = new BasicDBObject();
query.put("name","abc");
query.put("cities",up);
DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query);
But the result of this object contains the id . So i just need to get rid of that.
You need to give retrieved fields as the second parameter of findOne method
BasicDBObject retrievedField = new BasicDBObject();
retrievedField.put("_id",0);
dbcoll.findOne(query, retrievedField);
Also if you want to retrieve the exact query you shown I think you need to append elemMatch object to retrievedFields instead of adding it to queryObject.
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("cityName","A");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
retrievedField.append(up);
BasicDBObject query = new BasicDBObject();
query.put("name","abc");
DBCollection dbcoll = mongoTemplate.getCollection("sample");
DBObject object = dbcoll.findOne(query, retrievedField);

Mongo Database, SELECT * WHERE id = 3 AND id = 4

I have a MongoDB and I want to get two records or more records and put this in a map.
The code below works ok if I have just one query.put(ïd", "7"); but it doesn't work if I put two or more in like in the code below.
Map<Object,Object> map= new HashMap<Object,Object>();
DBCollection collection = database.getCollection("Members");
BasicDBObject query = new BasicDBObject();
query.put("id", "7");
query.put("id", "3");
DBCursor cursor = collection.find(query);
DBObject one;
while(cursor.hasNext()) {
one = cursor.next();
map.put(one.get("id"),one.get("name"));
}
How would I get would I get two or more records in the map?
For SQL the equivalent would be SELCT * FROM Member WHERE id = 7 AND id = 3
Even more perfect would be if I could give a list as a query, not sure if this is possible.
I think you want the $in operator, something like:
Map<Object,Object> map= new HashMap<Object,Object>();
DBCollection collection = database.getCollection("Members");
BasicDBObject query = new BasicDBObject();
query.put("id", new BasicDBObject("$in", new Integer[] {3, 7}));
DBCursor cursor = collection.find(query);
DBObject one;
while(cursor.hasNext()) {
one = cursor.next();
map.put(one.get("id"),one.get("name"));
}
...assuming the values are Integers. I think both arrays and BasicDBList instances are supported.

Categories