Mongo Java query for and/or combination - java

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());
}

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.

Queries in java mongodb API

I am new to mongodb java api. I am trying to perform queries to my database. I ve read the database found the collections in it and I want to retrieve characteristics of users. My code:
ServerAddress serverAdr;
serverAdr = new ServerAddress(".. .. .., ...);
Twitter twitter = null;
MongoOptions options = new MongoOptions();
options.connectionsPerHost = 10;
MongoClient mongoClient = new MongoClient(.. ... ...", ...);
DB db = mongoClient.getDB("trendSetters");
System.out.println("Connect to database successfully");
//JSONObject content = getJSONFromFile("user.json");
Mongo mongo = null;
Set<String> colls = db.getCollectionNames();
mongo = new Mongo(serverAdr, options);
mongo.setWriteConcern(WriteConcern.SAFE);
DB db_se = mongo.getDB("iti_se");
DBCollection incollection = db_se.getCollection("cms_users_unique");
DBCollection outcollection = db_se.getCollection("cms_users_features");
for (String s : colls) {
System.out.println(s);
}
Now I want to perform queries to retrieve from all ids the usernames for example. How is it possible to do so in java mongodb API?
EDIT: What i ve tried
BasicDBObject query = new BasicDBObject();
DBCursor cursor;
query = new BasicDBObject("followers", new BasicDBObject("$gt", 1));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
However, it doesnot return nothing.
You asked: "I want to perform queries to retrieve from all ids the usernames for example."
To retrieve all documents from collection you can use find() method of the DBCollection.
DBCursor cursor;
cursor = incollection.find();
After that, you can get the field value by its name for each document as below
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
If you need to add more criterias to query documents:
BasicDBObject query1;
DBCursor cursor;
query1 = new BasicDBObject("age", new BasicDBObject("$gt", 25));
cursor = incollection.find(query1);
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
DBCollections objects have method find which takes mainly a DBObject argument. For instance, if you want to find users with age > 50 this can help you.
query = new BasicDBObject("age", new BasicDBObject("$gt", 50));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
BasicDBObject take first argument, that is a field, and second argument that is another BasicDBObject or a value. With composition of these objects you can build any query.
I recommend you take a look at MongoDB Documentation, it's pretty good.
Mongo Java Driver http://docs.mongodb.org/ecosystem/drivers/java/
See Javadoc. http://api.mongodb.org/java/current/

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);

How to do this MongoDB query using java?

I have to write a simple MongoDB query using java but am not able to do it.
The mongo query looks like this:
db.yourCollection.find({"$where" : "this.startDate < this.endDate"})
I have to write the above query using the QueryBuilder class. But am not able to do it in MongoDB java driver.
BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("intValue", 1200);
document.put("updateValue", 2100);
DBObject query = QueryBuilder.start("intValue").lessThan("updateValue").get();
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());}
The above code does not return any results. But if changed to updateValue into 2100 it is giving result. My question here is lessThan takes object as input parameter. Then how can I pass document field as an input parameter?
Ideally your mongoDB query should be like this: -
db.yourCollection.find({"startDate": {$lt: endDate}})
which can be written in Java like this: -
BasicDBObject query = new BasicDBObject("startDate", new BasicDBObject("$lt", endDate);
DBCursor cursor = coll.find(query);
You can take a look at Official Tutorial
If you want to use QueryBuilder, you can do it like this: -
DBObject query = QueryBuilder.start("startDate").lessThan("endDate").get();
DBCursor cursor = coll.find(query);
QueryBuilder helps construct complex queries to retrieve data from a collection in mongo db.
You can use the QueryBuilder like this.
BasicDBObject document = new BasicDBObject();
QueryBuilder qb = new QueryBuilder();
qb.or(new QueryBuilder().put("starting_date").is(null).put("ending_date").is(null).get(),
new QueryBuilder().put("starting_date").lessThanEquals("ending_date").get());
document.putAll(qb.get());
DBCursor cursor = getDbCollection().find(document)
QueryBuilder qb = new QueryBuilder(), instantiates a new QueryBuilder.
The logic build by the QueryBuilder in the example above is; (starting date = null and ending date = null) or (starting date <=ending date)
document.putAll(qb.get()) adds the logic constructed to the DBObject.

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