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.
Related
{
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.
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 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);
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"}