How to extract only one value from mongoDB? - java

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);
}

Related

Get field of json from array of jsons

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));
}

Insert JSON Array into mongodb

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.

search Hbase record using java API?

I want to search record base on value and my application in Java
I am store record using below code
HTable table = new HTable(conf, tableName);
Put put = new Put(Bytes.toBytes(rowKey));
put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier),
Bytes.toBytes(value));
table.put(put);
I pass values
Put put = new Put(Bytes.toBytes("rowkey"));
put.add(Bytes.toBytes("family1"), Bytes.toBytes("qualifier1"),
Bytes.toBytes("this is test record"));
this is my get implementation
Get get = new Get(Bytes.toBytes("rowkey"));
String[] family = { "row1" };
get.addColumn(Bytes.toBytes("family1"),Bytes.toBytes("qualifier1"));
Result rs = table.get(get);
now I want to search this record by "this is test record" value.
help me to found this record.
using filter you can do search on any of the element and you can pass different combination
for SubstringComparator BinaryComparator
FilterList flist = new FilterList();
flist.addFilter(new RowFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("Predicatevalue"))));
flist.addFilter(new QualifierFilter(CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes("Subject value"))));
flist.addFilter(new ValueFilter(CompareOp.EQUAL,new BinaryComparator(Bytes.toBytes("Objectvalue"))));
This work for me.
Look at the get() method on HTable and the Get class, which are analogous to the put() method on HTable and the Put class.

How to upsert with mongodb-java-driver

How can I upsert data into mongodb collection with java-driver?
I try (with empty collection):
db.getCollection(collection).update(new BasicDBObject("_id", "12"), dbobject, true, false);
But document was created with _id == ObjectID(...). Not with "12" value.
This code (js) add document with _id = "12" as expected
db.metaclass.update(
{ _id:12},
{
$set: {b:1}
},
{ upsert: true }
)
mongo-java-driver-2.11.2
If you are using mongo-java driver 3, following .updateOne() method with {upsert, true} flag works.
void setLastIndex(MongoClient mongo, Long id, Long lastIndexValue) {
Bson filter = Filters.eq("_id", id);
Bson update = new Document("$set",
new Document()
.append("lastIndex", lastIndexValue)
.append("created", new Date()));
UpdateOptions options = new UpdateOptions().upsert(true);
mongo.getDatabase(EventStreamApp.EVENTS_DB)
.getCollection(EventCursor.name)
.updateOne(filter, update, options);
}
You cannot set _id if dbobject is just a document and does not contain an update operator eg: $set, $setOnInsert.
Just passing a document will replace the whole document meaning it doesn't set an _id a falls back to ObjectId
So your example works if you use an update operator eg:
db.getCollection(collection).update(
new BasicDBObject("_id", "12"),
new BasicDBObject("$set", new BasicDBObject("Hi", "world")), true, false)
You can use the replaceOne method and specify the ReplaceOptions (since 3.7) :
private static final ReplaceOptions REPLACE_OPTIONS
= ReplaceOptions.createReplaceOptions(new UpdateOptions().upsert(true));
db.getCollection(collection).replaceOne(new BasicDBObject("_id", "12"), dbobject, REPLACE_OPTIONS);
For older versions you can directly pass the UpdateOptions to the replaceOne method :
private static final UpdateOptions UPDATE_POLICY = new UpdateOptions().upsert(true);
db.getCollection(collection).replaceOne(new BasicDBObject("_id", "12"), dbobject, UPDATE_POLICY);
As mentioned in the documentation :
replaceOne() replaces the first matching document in the collection
that matches the filter, using the replacement document.
If upsert: true and no documents match the filter, replaceOne()
creates a new document based on the replacement document.
This is to upsert with scala driver which i couldnot find in web
con.updateOne(
equal("vendor_id", vendorId),
inc("views_count", f.views),
UpdateOptions().upsert(true))
to do so import the following
import org.mongodb.scala.model.UpdateOptions

CSV to GeoJSON conversion

I want to convert a CSV line into a GeoJSON object. I am using CSVReader. Hence, nextLine[] has all the separated tokens.
I want to create BasicDBObject which has various attributes stored. I am doing it following way.
new BasicDBObject("attribute1",nextLine[0]).append("attribute2",nextLine[1])
What I want to achieve is having a document like this in MongoDB
{
attribute1: name
attribute2: address
location:{ type : "Point" ,
coordinates : [lat, long]
}
attrribute3: phonenumber
}
How do I do this using BasicDBObject?enter code here
The easiest way to do that is using the BasicDBObjectBuilder, an utility class to build DBObjects. You can do something like that:
BasicDBObject toInsert = BasicDBObjectBuilder.start()
.add("attribute1",nextLine[0])
.add("attribute2",nextLine[1])
.add(" attrribute3",nextLine[2])
.push("location")
.add("type", "Point")
.add("coordinates", new double[] { nextLine[3], nextLine[4] })
.pop()
.get()
I did it the other way
double latLong[] = new double[]{10.0, 30.0};
BasicDBObject doc = new BasicDBObject("attr1",nextLine[0])
.append("attr2", nextLine[1]
.append("location",new BasicDBObject("type","Point")
.append("coordinates",latLong))
.append("attr3", nextLine[3])
This also works as desired

Categories

Resources