mongodb fetching all documents in the range of two dates - java

I have a mongo database containing documents in the following structure
{
_id:5e4f078e688bb974ed1dbc21
timestamp:"Mon Mar 06 23:54:55 EST 2017"
formatted_date:"2017-03-06 23:54:55"
steps:13
step_delta:13
}
I'm finding it tricky to get all documents (i believe there is a simple query for this, i'm just mistaken) that fall in between the specific dates needed.
this is my mongo db query
DBObject query = QueryBuilder.start().put("formatted_date").greaterThanEquals(startDate).and().put("formatted_date").lessThanEquals(endingDate).get();
Original, I was thinking it would be like the following sql query
String query = new StringBuilder("SELECT * FROM ").append(ACTIVITY_TABLE)
.append(" WHERE formatted_date BETWEEN ").append(startDate)
.append(" AND ").append(endDate).toString();
how do I make such a query in mongodb in java

You could create a range on the field formatted_date with this:
query = new BasicDBObject(
"formatted_date",
new BasicDBObject("$gte", startDate).append("$lte", endingDate)
);
cursor = collection.find(query);
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

Using MongoDB Java Driver the following code queries and prints the documents between the input fromDate and toDate of formatted_date field.
MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("testDB");
MongoCollection<Document> collection = database.getCollection("testColl");
String fromDate = "2020-02-06";
String toDate = "2020-02-09";
MongoCursor<Document> cursor = collection
.find(and(
gte("formatted_date", fromDate),
lte("formatted_date", toDate)))
.iterator();
cursor.forEachRemaining(System.out::println);
With the three input documents,
{ "_id" : 1, "formatted_date" : "2020-02-06 23:54:55", "steps" : 13 }
{ "_id" : 2, "formatted_date" : "2020-02-08 10:00:00", "steps" : 10 }
{ "_id" : 3, "formatted_date" : "2020-02-10 00:30:40", "steps" : 2 }
the output is:
Document{{_id=1.0, formatted_date=2020-02-06 23:54:55, steps=13.0}}
Document{{_id=2.0, formatted_date=2020-02-08 10:00:00, steps=10.0}}
Note the collection.find​(Bson filter) method builds the query's filter using the com.mongodb.client.model.Filters factory class's gte and lte methods.

Related

No results for $in clause in mongodb with java

I am trying to fetch few records based on list of ids. I am getting the results if I run the query directly on robomongo. But, the same doesn't work at code level in java.
Sample record:
{
"_id":"142",
"projectId":"PR_811",
"projectName":"ProjectTest007",
"entityName":"id-1412516",
"processName":"MSATesting",
"startDate":{
"$date":{
"$numberLong":"1666051200000"
}
},
"endDate":{
"$date":{
"$numberLong":"1666224000000"
}
},
"isRegulated":"No",
"tagNameList":[
],
"projectRole":{
"1464":"1464"
},
"projectPhase":{
"634e611de8ba26418e93ac96":"634e611de8ba26418e93ac96"
},
"status":"Approved"
}
BasicDBObject query = new BasicDBObject();
query.put("_id", new BasicDBObject("$in", projectIds)); //ProjectIds has list of ids as strings
DBCollection dbCollection = database.getCollection("Projects");
DBCursor cursor = dbCollection.find(query);
Not sure if I am missing something w.r.t in clause here.
some queries of robomongo vs our technical code method are different. For writing queries and searching in MongoDB check for $lookup command. Also you can just send id to model function and query it like collection.find(_id:id){ //results }

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.

Query on MongoDB fields

I am using MongoDB with java 3.0 driver. In the manual I only found find() and findOne() which will give me all the document.
I have a scenario like I should get the _id value by querying. for eg in SQL select _id from table name.
{
"_id" : ObjectId("557660c074cd60207e337aed"),
"contactMethodId" : [
{
"contactMethodId" : "contactMethodId",
"contactMethodUsageTypeCode" : null,
"contactMethodTypeCode" : "contactMethodTypeCode",
"contactMethodValue" : "contactMethodValue",
"contactContentTypeCode" : "contactContentTypeCode",
"contactContentMaxSize" : "contactContentMaxSize",
"comment" : "comment",
"preferredInt" : "preferredInd",
"effectiveStartDateOfContact" : "effectiveStartDateOfContact",
"effectiveEndDateOfContact" : "effectiveEndDateOfContact",
"standardizedIndOfContact" : "standardizedIndOfContact",
"lastVerifiedDateOfContact" : "lastVerifiedDateOfContact"
}
]
}
_id is generated by default.
I want something like select _id from table name and I should get ObjectId("557660c074cd60207e337aed") in java. Any suggestions.
MongoIterable<Document> = mongoClient.getDatabase("foo")
.getCollection("bob")
.find()
.projection(new Document("_id", 1))
You can use following :
BasicDBObject projection = new BasicDBObject();
projection.put("_id",1);
DBCursor cursor = collection.find(new BasicDBObject(),projection);
And then read using loop on cursor.
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());
}
Check this code, tested with mongo version 3.0.3 and Mongo Java driver version 3.0.1
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
public class demo {
public static void main(String[] args) throws Exception {
Mongo mongo = new Mongo("localhost", 27017); // set host and port of mongo
DB db = mongo.getDB("demo"); // set DB name
DBCollection collection = db.getCollection("collectionName"); // set collection Name
BasicDBObject query = new BasicDBObject();
BasicDBObject project = new BasicDBObject();
project.put("_id", 1); // set project to get _id
DBCursor cursorDoc = collection.find(query, project); // find query with projection
while(cursorDoc.hasNext()) {
BasicDBObject object = (BasicDBObject) cursorDoc.next();
String _id = object.get("_id").toString(); // If required convert the _id to String
System.out.println(object); // print _id with object
System.out.println(_id); // print _id as a String
}
}
}

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.

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

Categories