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
}
}
}
Related
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.
I want to get ID by a matching name in mongoDB in Java.
That's my code:
MongoClient mongo = new MongoClient();
DB db = mongo.getDB("test");
DBCollection groupTable = db.getCollection("Items");
searchQuery.put("name", "John");
DBCursor cursor = groupTable.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
But it shows the whole row containt the name John, what I want is the ID not the whole thing.
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"name":John,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-}
Any help?
Thanks
It's very simple, just select the id...
while (cursor.hasNext()) {
System.out.println(cursor.next().get("_id"));
}
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 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.
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"}