How to identify document in MongoDB in Java - java

I am wondering if MongoDB provide some good schema for identifying documents in the database. Suppose I have initialized a database like this:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
}
Now How can I get the "document" inserted in the database? I already know a key/value pair query can locate the document, like:
BasicDBObject query = new BasicDBObject();
query.put("name", "Mike");
DBObject dbObj = coll.findOne(query);
Is there another way other than this kind of key/value pair query to identify the document?
If you want to identify a collection, you can do it by match the collection name:
DBCollection coll = db.getCollection("mycollection");
I hope there is something like this to identify the document. Any suggestion?

If you look in the document object after the coll.insert(document); you will find that a _id field was added by the driver. You can use this field/value to query for the exact document since MongoDB enforces there must be an _id field and it must be unique.
Putting this all together:
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("testdb");
DBCollection coll = db.getCollection("mycollection");
BasicDBObject document = new BasicDBObject();
document.put("name", "Mike");
document.put("age", 25);
coll.insert(document);
System.out.println(document.get("_id"));
BasicDBObject query = new BasicDBObject();
query.put("_id" , document.get("_id"));
DBObject retrieved = collection.findOne(query);
System.out.println(retrieved);
}

Related

Combine two mongoDB queries in Java

Below is the code I have:
//Creating a mongo client and connecting to the database and getting the collection from the table in database
MongoClient mongoClient = new MongoClient("000.1.1.26", 27017);
MongoDatabase databases = mongoClient.getDatabase("DBName");
System.out.println("Connected to the database successfully");
MongoCollection<Document> collection = databases.getCollection("TableName");
// Retrieving Column-wise data for fieldName from database
BasicDBObject searchQuery = new BasicDBObject();
FindIterable<Document> testColumn=collection.find().projection(Projections.fields(Projections.include("fieldName"), Projections.excludeId()));
//We have to run this command(Here I have merged 2 commands )
AggregateIterable<Document> iterDoc = collection.aggregate(Arrays.asList(Aggregates.group("$Id", Accumulators.max("logDate", 1)), project(Projections.fields(Projections.include("fieldName"), Projections.excludeId()))));
The above joint query is giving me below error:
The method project(Bson) is undefined for the type
Any help for this?

Use Of $slice Query while fetching data from mongodb in JAVA

I have a small query which is giving the result while invoking it on mongo database. But when I am using this in JAVA for fetching the data then it giving me exception.
Below is the query :
db.collectionName.find({'name': 'Sam'},{"Address": { "$slice": -1 } })
In database, name is the key and address is the list containing lets say 4 number of addresses.We want to fetch the updated address in "Address" KEY.
Below is the java code which we are using :
final DBCollection dbCollection = mongoTemplate.getCollection("apMonitoringData");
final BasicDBObject query = new BasicDBObject();
query.put("name", "sam");
query.put("address", new BasicDBObject("$slice", -1));
final BasicDBObject sortQuery = new BasicDBObject();
// Sorting in Descending order for last updated entry
sortQuery.put("_id", -1);
final DBCursor dbCursor = dbCollection.find(query).sort(sortQuery).limit(1);
DBObject dbObject = null;
while (dbCursor.hasNext()) {
dbObject = dbCursor.next();
}
return dbObject;
but it is giving error as
com.mongodb.MongoException: Can't canonicalize query: BadValue: unknown operator: $slice
Can anybody please look into this.
You will need to separate the query from the fields.
Also, use append when you want to add entries to a document instead of put
BasicDBObject query = new BasicDBObject("name","sam");
BasicDBObject fields = new BasicDBObject("address",new BasicDBObject("$slice", -1));
collection.find(query,fields).sort(sortQuery).limit(1);

Query the most recent entries in a collection in Java

This mongodb query below returns the most recent entries to a collection
db.RSS.find().limit(6).sort({$natural:-1}).pretty()
Does anyone know how to implement this query in Java?
Using Mongo-Java Driver, this code is an example:
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("RSS");
FindIterable<Document> it = collection.find().limit(6).sort(new Document().append("$natural", -1));
MongoCursor<Document> cursor = it.iterator();
while(cursor.hasNext()){
Document doc = cursor.next();
System.out.println(doc.toJson());
}

writing mongoDB syntax

hey guys how to write this mongoDB syntax to java
db.users.find( { user_id: /bc/ },{user_name:/bc/},{age:/2/} )
my source is
BasicDBObject sortOrder = new BasicDBObject();
MongoClient mongoClient;
DB db;
DBCollection table;
DBCursor cursor = null;
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("stackoverflow");
boolean auth = db.authenticate("aku","kamu".toCharArray());
table = db.getCollection("questions");
cursor = table.find();
while (cursor.hasNext()) {
DBObject object = cursor.next();
out.print(object.get("title"));
answer = rn.nextInt(8) + 0;
}
any solution guys?
i am newbie on using mongoDB
DBObject idMatch = new BasicDBObject("user_id","bc");
DBObject usernameMatch = new BasicDBObject("user_name",bc);
DBObject ageMatch = new BasicDBObject("age",2);
DBObject andAll = new BasicDBObject("$and", Arrays.asList(existence, firstNotMatch, secondNotMatch));
//calling table.find will get you what you wanted.
table.find(andAll);
If you want to 'OR' the conditions, just replace $and with $or.
note that the above code is not tested properly and you may need to modify it a bit to make it work.
Your question is not clear, but i hope i helped.

Java + MongoDB: Updating multiple fields in a document

I am trying to update at once multiple fields in a single MongoDB document, but only one field is updated.
I have a collection user, in which users are uniquely defined by a customer_user_id. I want to update a certain user's birth_year and country fields.
This is what I am doing:
// Define the search query:
DBCollection col = md.getDb().getCollection("user");
BasicDBObject searchQuery = new BasicDBObject("customer_user_id", customer_user_id);
// Define the update query:
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("birth_year", birth_year);
updateQuery.append("$set", new BasicDBObject().append("country", country);
log.info("Update query: " + updateQuery);
col.update(searchQuery, updateQuery);
Unfortunately, only the country field is updated, and the logged updateQuery looks like this:
Update query: { "$set" : { "country" : "Austria"}}
I cannot verify that but maybe you should try:
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("birth_year", birth_year);
updateFields.append("country", country);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
col.update(searchQuery, setQuery);
or this is pretty the same I think:
updateQuery.put("$set", new BasicDBObject("country",country).append("birth_year", birth_year));
Alternatively, there are convenience methods in com.mongodb.client.model.Updates to do this:
MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");
collection.updateMany(
Filters.eq("customer_user_id", customer_user_id),
Updates.combine(
Updates.set("birth_year", birth_year),
Updates.set("country", country)
));
Underlying this will create a Bson query with $set as well, but using convenience methods keeps your code more clear and readable.
For MongoDB 3.4 you can use
MongoCollection<Document> collection = database.getCollection(nameOfCollection);
Bson filter = new Document("SearchKey", Value);
Bson newValue = new Document("UpdateKey1", "Value1").append("UpdateKey2", "Value2")....;
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateMany(filter, updateOperationDocument);
A variation on answer by #pakat...
MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");
List<Bson> updatePredicates = new ArrayList<Bson>();
Bson predicateBirthYear = set("birth_year", birth_year);
Bson predicateCountry = set("country", country);
updatePredicates.add(predicateBirthYear);
updatePredicates.add(predicateCountry);
collection.updateMany(Filters.eq("customer_user_id", customer_user_id), Updates.combine(updatePredicates));

Categories

Resources