Find ancestors in mongodb with Java - java

In the mongo shell I retrieve ancestors of an element (I built a tree structure with an array of ancestors) using this query:
db.collection.findOne({_id: "some_unique_id"}).ancestors
What is the equivalent code in Java?
My code that doesn't get the right result is:
BasicDBObject root = new BasicDBObject();
root.put("_id", idObj);
root.put("type", typeObj);
BasicDBObject query = new BasicDBObject("ancestors", root);
DBObject o = locations.findOne(query);
System.out.println(idObj + " - findone => " + o.toString());
Where is the error?
Thanks in advance

The Java equivalent to your mongo shell query is:
BasicDBObject query = new BasicDBObject("_id", "some_unique_id");
DBObject o = locations.findOne(query);
System.out.println(o.get("ancestors"));

Related

MongoDB shell query on timestamp range not working in java

The following query in the mongoDB shell
db.getCollection('Consolidated Records').find({'timestamp': {$gte: 1500000036316, $lte:1500001136316}})
is working and returns several records.
The same query in Java as follows:
long firstTimestamp = 1500000036316L;
long lastTimestamp = 1500001136316L;
BasicDBObject query = new BasicDBObject("timestamp", new BasicDBObject("$gte", firstTimestamp).append("$lte", lastTimestamp));
DBCursor oneDayCursor = collection.find(query);
doesn't return any results when called on the same DB collection.
Any idea what is wrong with the Java code?
What is the version of MongoDB ?
If you are using 3.x you could use below code
FindIterable<Document> findCursor = newCol.find(Filters.and(
Filters.gte("firstTimestamp", firstTimestamp),
Filters.lte("lastTimestamp ", lastTimestamp )));

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

can we update a document in mongodb using _id in java?

I am trying update document with object id but not getting result. Here is my code please help me
DBCollection patients= db.getCollection("Patients");
BasicDBObject doc = new BasicDBObject();
doc.put("name","seshu");
DBObject update=`new` BasicDBObject().append("_id",ObjectId("534e1c8e40a8af540cd01ff4"));
patients`enter code here`.update(update, doc);
When you say "not getting result", I assume you mean that the document is not being updated?
Are you sure that you have the collection name, database name, and ObjectId correct? And that a document exists in that collection with that ObjectId. You should double check all of this via your program or the mongo shell.
Why don't you also try adding some extra checks/debugging in your code, something like this:
DBCollection patients = db.getCollection("Patients");
DBObject update = new BasicDBObject().append("_id", new ObjectId("..."));
long collectionCount = patients.count();
System.out.println(String.format("Collection count: %s", collectionCount));
long count = patients.count(update);
System.out.println(String.format("Count for query: %s", count));
BasicDBObject doc = new BasicDBObject();
doc.put("name", "seshu");
WriteResult writeResult = patients.update(update, doc);
System.out.println(String.format("Updated %s records", writeResult.getN()));
DBObject updated = patients.findOne(update);
System.out.println(updated);

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.

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