Mongodb java input date between two date fields - java

I would like to create a query such as :
SELECT * FROM MY_TABLE WHERE {MY_DATE_1} BETWEEN {DB_COLUMN_1} AND
{DB_COLUMN_2} OR {MY_DATE_2} BETWEEN {DB_COLUMN_1} AND {DB_COLUMN_2})
I know how to do the opposite ( a field between two variables), since BasicDBObject takes a string (I guess the field name) as first parameter and not a date. Thank you !

I guss you want to use $or to query like the sql
here is the demo with java
BasicDBObject query = new BasicDBObject();
BasicDBObject condition1 = new BasicDBObject("fieldA",new BasicDBObject("$gt","2018-06-02 12:20:00").append("$lt","2019-06-02 12:20:00"));
BasicDBObject condition2 = new BasicDBObject("fieldB",new BasicDBObject("$gt","2018-06-02 12:20:00").append("$lt","2019-06-02 12:20:00"));
BasicDBList condList = new BasicDBList();
condList.add(condition1);
condList.add(condition2);
query.put("$or" ,condList);
collection.find(query);
the $gt means greater than and $lt means less than .

Related

partially update fields in a document - findAndModify remove all other fields?

When using MongoTemplate - collection.findAndModify It will delete all document fields, and leave only the updated column/s.
Why is that?
How to partially update fields in a document?
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject("phoneNumber","404-525-3928");
DBObject result = collection.findAndModify(query, update);
At this point - all fields removed from company 1...
The workaround will be to go to the DB, fetch company 1 document update the field/s and save it...,
But what if i need to update 10K of them?
You need the $set operator in the update document. You use that and other update operators here otherwise what you specify will replace whatever the document currently contains:
DBCollection collection = mongoTemplate.getCollection("company");
DBObject query= new BasicDBObject("companyId","1");
DBObject update= new BasicDBObject(
"$set", new BasicDBObject("phoneNumber","404-525-3928")
);
DBObject result = collection.findAndModify(query, update);

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.

How can I build an $or query for MongoDB using the Java driver?

I'm trying to Or some conditions in MongoDB (using the Java driver). This is what I'm doing :
Pattern regex = Pattern.compile("title");
DBCollection coll = MongoDBUtil.getDB().getCollection("post_details");
BasicDBObject query = new BasicDBObject();
query.put("category_title", "myCategory");
query.append("post_title", regex);
query.append("post_description", regex);
DBCursor cur = coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next().get("post_id"));
}
I'd like to use the $or operand on these conditions, but I guess the default is "and" and I don't know how to change it. In the above code if one of the conditions returns null, the result will be null too.
You are correct that the "default" for specifying multiple field in a query is that each field serves as a conditional filter, and thus is an AND operation.
You can perform MongoDB queries with an OR clause by using the $or operand which has the following syntax :
db.col.find({$or:[clause1, clause2]})
Where each clause can be a query. $or does not have to be a top level operand but if it is MongoDB can use an index for each seperate clause.
In your example you want to end up with this query :
db.col.find({$or:[{"post_title", regex}, {"post_description", regex}]});
Which can be constructed in Java through :
DBObject clause1 = new BasicDBObject("post_title", regex);
DBObject clause2 = new BasicDBObject("post_description", regex);
BasicDBList or = new BasicDBList();
or.add(clause1);
or.add(clause2);
DBObject query = new BasicDBObject("$or", or);
With filters you could build yours like:
import com.mongodb.client.model.Filters;
...
Bson filter = Filters.or(
Filters.eq("post_title", regex),
Filters.eq("post_description", regex)
);

How to query for only a certain attribute

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"}

Query Syntax in mongodb for sql "like" - i am using java

basically this is my question:
How to query MongoDB with "like"?
but i guess all the answers in here are applicable when you are using mongodb shell command line, so what is the equivalent for db.users.find({"name": /.*m.*/}) when we are using java.
here is how i am trying to do
DBCollection coll = MongoDBUtil.getDB().getCollection("post_details");
BasicDBObject query = new BasicDBObject();
query.put("price", new BasicDBObject("$gt", 5).append("$lt", 8));
/*what should i write instead of this line*/
query.put("title", "/.*m.*/");
DBCursor cur = coll.find(query);
For this issue you should use a regex as in this example:
BasicDBObject query = new BasicDBObject();
Pattern regex = Pattern.compile("the title you are looking for"); // should be m in your case
query.put("title", regex);
Taking the above example as reference, but using the Filters class:
Pattern regex = Pattern.compile("title you look for");
Bson filter = Filters.eq("nombre", regex));

Categories