I have the following json document. I want to retrieve only all the names. Given a movie name I need to return all the user names.
I am using Java, if you can also assist me in Java it will be awesome. How can I do this?
You can use something like if you're using Mongo 3.x driver.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> movieToUsers = db.getCollection("movieToUsers");
Bson filter = Filters.eq("movieName", "Green Mile");
List<String> names = movieToUsers.distinct("user.name", filter, String.class).into(new ArrayList<>());
You org.json library
sample
//Json object
JSONObject obj = new JSONObject(" .... ");
String id = obj.getString("_id");
String movieName = obj.getString("movieName");
//Json array
JSONArray users = obj.getJSONArray("user");
for (int i = 0; i < arr.length(); i++)
{
String name = user.getJSONObject(i).getString("name");
String name = user.getJSONObject(i).getString("date");
}
You can use distinct() function with a query as follows:
mongo shell:
var results = db.movieToUsers.distinct("user.name", { "movieName": "Green Mile" });
printjson(results);
In Java, this is implemented by the distinct() method, for example
// Get a new connection to the db assuming that it is running
MongoClient m1 = new MongoClient();
// use test as a database or use your own database
DB db = m1.getDB("test");
// fetch the collection object
DBCollection coll = db.getCollection("movieToUsers");
// call distinct method with the query and store results in variable results
List results = coll.distinct("speed", new BasicDBObject("movieName", "Green Mile"));
// iterate through the results list and print the names
for(int i=0;i<results.size();i++){
System.out.println(results.get(i));
}
Related
Currently I am on the latest version of MongoDB and coding in Java. I am trying to update multiple documents at a time, but I need to find the corresponding document first after reading from a json file. I can do this one at a time, but I have about 6million documents that I need to search and update so wanted to do this properly.
This is how the Database looks like. I am searching by lifeId
{
"_id" : "wwwww",
"mId" : "xxxxx",
"lifeId" : yyyyy
}
Below is my json file:
{
"Items":
[
{"gseid":xxxxx,"mlifeno":xxxx,"firstname":"xxx","lastname":"xxx","emailaddress1":"xxxx#hotmail.com","dateofbirth":"06-AUG-60 12.00.00.000000000 AM","phonenumber":"xxxxxx","phonetype":"Home","street1":"xxxxx","city":"xxxxx","postalcode":"xxxx","preferred":1,"addresstype":"Home"}
,{"gseid":xxxx,"mlifeno":xxx,"firstname":"xxx","lastname":"xxx","emailaddress1":"xxxx#msn.com","dateofbirth":"07-AUG-48 12.00.00.000000000 AM","phonenumber":"xxxx","phonetype":"Mobile","street1":"xxxxx","city":"xxx","postalcode":"xxx","preferred":1,"addresstype":"Home"}
,{"gseid":xxxx,"mlifeno":xxx,"firstname":"xxx","lastname":"xxx","emailaddress1":"xxx#yahoo.com","dateofbirth":"06-MAR-71 04.00.00.000000000 PM","phonenumber":"xxxx","phonetype":"Home","street1":"xxxxx","street2":"xxxxx","city":"Bolingbrook","postalcode":"xxxx","preferred":1,"addresstype":"Home"}
]
}
I loop through the json file and can insert one at a time, but what I want to know is if it's possible to insert multiple (maybe 1000 at a time). I am searching by "mlifeno" in the json file and matching it to "lifeId" in the DB.
The below code iterates through the json file items
JSONArray itemsArr = (JSONArray) itemsObj.get("Items");
for(Object temp : itemsArr){
JSONObject d = (JSONObject) parser.parse(String.valueOf((JSONObject)temp));
Long mlifeno = Long.parseLong(String.valueOf(d.get("mlifeno"))); //mlifeno
// findAndAddCol(mlifeno,database,d); //find a document by mlifeno and update the columns
}
}
The below is where I find the database document and insert, one by one (which is what I don't want)
public static void findAndAddCol(Long mlife, MongoDatabase database, JSONObject temp){
MongoCollection<Document> collection = database.getCollection("CrosswalkColl");
JsonWriterSettings prettyPrint = JsonWriterSettings.builder().indent(true).build();
Bson filter = eq("lifeId",mlife); //find document by life number
//Update profile object after all inserted into object
BasicDBObject updateFields = new BasicDBObject();
JSONObject jsonPro = new JSONObject();
JSONArray arrPro = new JSONArray();
JSONObject last = new JSONObject();
temp.forEach((key,value) -> {
//Don't add life number or gseid to profile object
if(key.toString().equals("mlifeno")){
}else if(key.toString().equals("gseid")){
//add gseid
// Bson updateOperation = set(key.toString(),value);
updateFields.append(key.toString(),value);
}else{
jsonPro.put(key.toString(),value);
}
});
updateFields.append("Profile",jsonPro);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
//List with Batch Operation
UpdateResult updateResult = collection.updateOne(filter, setQuery); //this will search for the correct document and update
The code above works, but what I want to do is loop through maybe a 1000 at a time and bulkwrite them instead of having to do this one by one.
I using a MongoCollection as following code :
MongoDatabase conn = getMongoConnection(DbName);
MongoCollection collection = conn.getConnection(CollectionName);
List<BasicDBObject> query = new ArrayList();
if (searchKey.containsKey("filter1")) {
String filter1= (String) searchKey.get("filter1");
query.add(new BasicDBObject("filter1", filter1));
}
if (searchKey.containsKey("filter2")) {
String filter2= (String) searchKey.get("filter2");
query.add(new BasicDBObject("filter2", filter2));
}
int rowAmount = (int) collection.count(new BasicDBObject("$and", query));
rowAmount gets the correct amount of data, but I want to know an actual query when it got the result. Any ideas how?
You can see actual queries sent to the server via command monitoring.
LIKE I HAVE THREE FIELD 'TO','FROM' AND 'MESSAGE', I just want to display content of message field where I have given some clause in to and from.
Document{{_id=59c7d57c674cd5673c304936, to=9915103230, from=9915103229, date=24/12/2017, message=HELLO WORLD}}
I JUST WANT TO RETRIEVE "HELLO WORLD", not the whole document.
Like I just want, String message=?????---> I need some method here so the Variable of String type gets the value Hello World.
Projection method is not working for me.
I am using JDBC MongoDB 3.5 Driver.
Use projection, the second optional argument to find(). For context, this gives you the whole document:
db.yourCollection.find({to:9915103230,from:9915103229});
This gives you only message from the results. Just name the field and set it to 1:
db.yourCollection.find({to:9915103230,from:9915103229},{message:1};
You can specify more than one thing to return:
db.yourCollection.find({to:9915103230,from:9915103229},{message:1, to:1};
Here's a functioning prog. Compile against the 3.5 drivers.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase( "testX" );
MongoCollection<BsonDocument> coll = db.getCollection("foo", BsonDocument.class);
coll.drop();
{
BsonDocument doc = new BsonDocument();
doc.put("from", new BsonInt32(23343223));
doc.put("to", new BsonInt32(23343223));
doc.put("msg", new BsonString("hello"));
coll.insertOne(doc);
doc.remove("_id");
doc.put("from", new BsonInt32(8889));
doc.put("to", new BsonInt32(99999));
doc.put("msg", new BsonString("goodbye"));
coll.insertOne(doc);
}
{
BsonDocument query = new BsonDocument("from", new BsonInt32(8889));
BsonDocument proj = new BsonDocument("msg", new BsonInt32(1));
proj.put("_id",new BsonInt32(0));
BsonDocument d2 = coll.find(query).projection(proj).first();
System.out.println(d2);
String s2 = coll.find(query).projection(proj).first().getString("msg").getValue();
System.out.println(s2);
}
I'm trying to insert a string that represents a JSON array into a mongodb collection with this,
String str = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
DBObject dbObject = (DBObject) JSON.parse(str);
collection.insert(dbObject);
But I get the exception,
Exception in thread "main" java.lang.IllegalArgumentException: BasicBSONList can only work with numeric keys, not: [_id]
Can anyone show me the correct way to do this?
String json = "[{\"id\":1,\"data\":\"data1\"},{\"id\":2,\"data\":\"data2\"},{\"id\":3,\"data\":\"data3\"}]";
MongoCredential credential = MongoCredential.createCredential("root", "sample", "root".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential));
MongoDatabase db = mongoClient.getDatabase("sample");
MongoCollection<Document> collection = db.getCollection("loginTracking");
List<Document> jsonList = new ArrayList<Document>();
net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(json);
for (Object object : array) {
net.sf.json.JSONObject jsonStr = (net.sf.json.JSONObject) JSONSerializer.toJSON(object);
Document jsnObject = Document.parse(jsonStr.toString());
jsonList.add(jsnObject);
}
collection.insertMany(jsonList);
mongoClient.close();
as per java doc the insert() can accept either single DBObject or an array or List of them.
So, in order to save, you need to convert your JSON array into an array/List of DBObjects, or save each array's item
I found a good way for achieve that:
(ArrayList<Document>) JSON.parse("[String json array]");
I had a problem with this, because i need append to this document a property that is a Json Array:
Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", My Array here!);
But the problem is that Document.parse() doesn't work with Arrays, so i could solve it using the above line. So the final code is:
Document objAddendumVersion = new Document();
objAddendumVersion.append("_id", new ObjectId());
objAddendumVersion.append("Array", (ArrayList<Document>) JSON.parse("[String json array]"));
And it works perfect. Yes i know that exist more better ways for do that, but for the moment i'm using this.
I wait that be useful for someone with the same trouble.
I am trying to do fetch the data from database using ScrollableResults. Part of my code is below :
List list = null;
ScrollableResults items = null;
String sql = " from " + topBO.getClass().getName(); // topBO is my parent class so i pass the any of my child class name .
StringBuffer sqlQuery = new StringBuffer(sql);
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery.toString());
items = query.scroll();
int i = 0;
TopBO topBO;
while(items.next())
{
topBO= (TopBO) items.get()[i];
list.add(TopBO2); // got the exception at this line.
i++;
topBO= null;
}
items.close();
If i run the above code i am getting runtime error like java.lang.NullPointerException
You are trying to add the value in list which is not initialize.
It may helps you :
List list = new ArrayList();
replace with
List list = null;
I think topBO= (TopBO) items.get()[i]; is causing the problem.
I would suggest that you use result set transformer of query something like this
Query query = sessionFactory.getCurrentSession().createQuery(sqlQuery.toString());
list=query.setResultTransformer(Transformers.aliasToBean(YourClassName.class)).list();