Stuck with an issue here.
I have 2 or more mongodb collections which need to be searched and the result of the search should be put into a JSON string.
// First collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionOne.find(dbo);
// Second collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionTwo.find(dbo);
The structure of the of the collection are not the same, but they do have a few common field, like 'transport','title', 'id' which are the fields that need to go in the json.
So combine the results of two searches into a single JSON response.
How would I do this?
Thanks for any help or suggestions!
Given the facts that the query criteria is unique across the collections, and MongoDB is a schema-free, no-SQL database, Actually you can just use one collection for all the data sets and don't need to consolidate different collections at all. Just like:
BasicDBObject query = new BasicDBObject();
query.append("transport", "car");
BasicDBObject fields = new BasicDBObject();
fields.append("transport", "1");
fields.append("title", "1"); //get the fields
DBCursor cur = collection.find(query, fields);
Related
i am trying to get distinct values from mongodb with java
in particular unique id but i dont found this .
DB database = MongoConnection.getInstance();
DBCollection collection = database.getCollection("licence_entery_fl3_fl1");
BasicDBObject wheremap = new BasicDBObject();
wheremap.put("int_distillery_id", act.getDist_id());
wheremap.put("vch_licence_type", act.getVch_to());
wheremap.put("vch_lic_unit_type", "D");
DBCursor cursor = collection.find(wheremap);
Iterator<DBObject> itr = cursor.iterator();
log.info("Fetching all documents from the collection licence_entery_fl3_fl1 ---------"+itr);
while(itr.hasNext()){
DBObject record = itr.next();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
Mongo_GatepassToWholesale_20_21_Model model = mapper.readValue(record.toString(), Mongo_GatepassToWholesale_20_21_Model.class);
System.out.println("--licence_nmbr.--"+model.licence_nmbr+"---");
item.setValue(model.vch_licence_no);
item.setLabel(model.licence_nmbr);
list.add(item);
}
this is implement for jsf .
please help me
I think the easiest way is to use spring data as an ORM with a specific datasource, so you can go through criteria like the following using regex :
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query,User.class);
or to have a select by identifier only used the MongoRepository interface by a findDistinctById() as ou can see here -- see chapter 6.3. Query methods --
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);
This is my document, that i want to get.
{"_id": {"$oid": "5747f303631e1e261019914d"},
"school": "aaa", "name": "Kamal", "likes": 200}
I want to get this only by passing its _id without giving its collection.
public DBObject findDocumentById(String id) {
BasicDBObject query = new BasicDBObject();
query.put("_id", new ObjectId(id));
DBObject dbObj = collection.findOne(query);
return dbObj;
}
As I am searching for different documents in different collections, I don't want to say in which collection does the _id belongs. So without saying collection.findOne(query).
How to get the documents?
You must mention what is the Collection. But you can try this.
for(String collectionName : mongoOperation.getCollectionNames()){
DBCollection collection = mongoOperation.getCollection(collectionName);
DBObject query = new BasicDBObject();
query.put("_id", new ObjectId(id));
DBCursor cursor = dbCollection.find(query);
if(cursor.hasNext()){
//match
//do something
break;
}
}
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));
Let's take an example of facebook posts where multiple users give likes to a post. Now for some post currently database stores 10 likes and if two users liked that post concurrently then both will read 10 as current like and update 11 one by one but the correct value should be 12. How to achieve this using mongodb and java.
Check the operator $inc.
Here is a sample code from this link:
// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");
// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);
// insert it into the collection
collection.insert(temp);
// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);
// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");
// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);