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 }
Related
I have the following code and my aim is to retrieve the documents which have the given tags.
String myText = "It is the first #example and is very #important";
ArrayList<String> tags = textProcessor.getTags(myText);
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("myFirstDatabase");
DBCollection table = db.getCollection("firstCollection");
BasicDBObject document = new BasicDBObject();
document.put("Text", myText);
document.append("tags", tags);
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("tags", "#important");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
It does not work, because the tagsis an array and I am searching for an element in the array. How can I retrieve the documents which have the given tag (in this case "important") directly?
I know that I can extract all the tags of all documents and then compare them in a loop. But I would like to do that directly.
In the meantime, I am completely new to mongodb. If there is a better way to insert tags in the database (so that, its retrieving is easier), I would be grateful to know.
Thanks in advance,
Mongodb list can be queried through a single string query just fine, you should check the textProcessor.getTags and check the data in the mongodb. I also suggest you to use spring-data-mongodb since it is much simpler and easier to learn.
My code need to support any query that being sent by the client . The client will be sending the query as a json . I have done this using java mongo driver low level api using following code , BasicDBObject queryObject = (BasicDBObject) JSON.parse(whereJson.toString());
As i am a newbie in spring data mongodb , i am unable to find a similar solution in either Query or Criteria classes . I have checked different tutorials and couldn't find any . Is it possible to do in spring data mongodb or should i use low level apis itself ?
You can create Query instances from a plain JSON String by using BasicQuery object. The following example demonstrates how you can construct a Query instance from a plain JSON String:
BasicQuery query = new BasicQuery("{ age : { $lt : 50 } }");
List<Person> result = mongoTemplate.find(query, Person.class);
Another way which uses the low-level API:
DBObject dbObject = (DBObject) JSON.parse(query);
DBCursor cursor = mongoTemplate.getCollection("person").find(dbObject);
You can then map the return objects back to your Person POJO using the MongoConverter read() method:
List<Person> returnList = new ArrayList<Person>();
while (cursor.hasNext()) {
DBObject obj = cursor.next();
Person person = mongoTemplate.getConverter().read(Person.class, obj);
returnList.add(person);
}
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/
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.
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)
);