Insert a document in a document - java

Im using mongodb + java. I tried to insert a new document into an existing document. Lets say I have a collection "Users":
{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :"null"}
Now I would like to update this document where the name == Klaus and add a new document to the key adress (wheres now only "null"). So I would like to have something like this:
{"_id" :{"$oid" : "4dc9..."}, "name" :"Klaus", "gender" :"unknown", "adress" :{"country" :"Austria", "city": "..."}}
How to do it in Java? I tried
//DBCollection col "Users"
String json = "{'country': '" + user.country + "', 'city': '" + user.city + "'}";
DBObject dbObject = (DBObject)JSON.parse(json);
col.update(new BasicDBObject().append("name", "Klaus"), dbObject); //not working
I dont get any errormessage, the new document is just not there. Is something wrong with my json? Or do I need another "update" function, maybe a replace (replace adress:null with adress:new document)? Thanks for any help!

Look at your update. At no point do you even specify there should be a field "address". Also note that you're not "inserting" a document within a document here. Rather your setting a field of your top level document to a value that is an embedded document. Use this instead :
col.update(new BasicDBObject("name", "Klaus"), new BasicDBObject("$set", new BasicDBObject("address", dbObject)));

Related

How to change name of a field in MongoDB with java for each document in the collection?

Due to some decisions I will have to change the name of some fields in all documents in a single collection. For purpose of automation testing I am inserting documents and then checking some logics.
Lets assume that after the insert method I have the following objects:
"_id" : ObjectId("60c10042d"),
"Name" : Mike,
"years" : 25,
"Country" : England
},
{
"_id" : ObjectId("40r10042t"),
"Name" : Smith,
"years" : 32,
"Country" : England
}
When inserting the document/documents I want to change the field "Country" to "Occupation" using Java. Here is example of the code I'm using:
MongoCollection<Document> documentMongo = MongoDb.getCollection("collectionName");
Document document = Document.parse(readJsonFile(json));
//I've tried this way:
//documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));
//didn't work
documentMongo.insertOne(document);
Oh, the rename should be after the insert is done.
documentMongo.insertOne(document);
documentMongo.updateMany(document, Updates.rename("Country", "Occupation"));
Anyway, it could help others which are searching for easy way to change field names.
Sadly, when I try rename more fields it works only for the first one.
Final solution:
documentMongoCollection.insertOne(document);
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$rename",new BasicDBObject().append("oldField", "newField").append("oldField1", "newField1").append("oldField2", "newField2"));
documentMongoCollection.updateMany(searchQuery,updateQuery);

How to custom search for text query in mongodb?

I'm new in mongodb. I have following data as a JSON format in mongodb. I need to search the bookLabel or the shortLabel for the book and it should show me all the information about the book. For example: if I query for 'Cosmos' it'll show all the description about the book, like: bookLabel, writer, yearPublish, url. How can I do that in java? Need query, please help.
"Class":"Science",
"Description":[
{
"bookLabel":"Cosmos (Mass Market Paperback)",
"shortLabel":"Cosmos",
"writer":"Carl Sagan",
"yearPublish":[
"2002"
],
"url":"https://www.goodreads.com/book/show/55030.Cosmos"
},
{
"bookLabel":"The Immortal Life of Henrietta Lacks",
"shortLabel":"Immortal Life",
"writer":"Rebecca Skloot",
"yearPublish":[
"2010, 2011"
],
"url":"https://www.goodreads.com/book/show/6493208-the-immortal-life-of-henrietta-lacks"
}
],
"Class":"History",
"Description":[
{
"bookLabel":"The Rise and Fall of the Third Reich",
"shortLabel":"Rise and Fall",
"writer":"William L. Shirer",
"yearPublish":[
"1960"
],
"url":"https://www"
}
]
}
With MongoDB Java Driver v3.2.2 you can do something like this:
FindIterable<Document> iterable = collection.find(Document.parse("{\"Description.shortLabel\": {$regex: \"Cosmos\"}"));
This returns all documents containing Cosmos in the Description.shortLabel nested field. For an exact match, try this {"Description.shortLabel": "Cosmos"}. Replace shortLabel with bookLabelto search the bookLabel field. Then you can do iterable.forEach(new Block<Document>()) on the returned documents. To search both bookLabel and shortLabel, you can do a $or{}. My syntax could be wrong so check the MongoDB manual. But this is the general idea.
For this, you can use MongoDB's Text Search Capabilities. You'll have to create a text index on your collection for that.
First of all create a text index on your collection on fields bookLabel and shortLabel.
db.books.createIndex({ "Description.bookLabel" : "text", "Description.shortLabel" : "text" })
Note that this is done in the Mongo shell
Then
DBObject command = BasicDBObjectBuilder
.start("text", "books")
.append("search", "Cosmos")
.get();
CommandResult result = db.command(command);
BasicDBList results = (BasicDBList) result.get("results");
for(Object o : results) {
DBObject dbo = (DBObject) ((DBObject) o).get("obj");
String id = (String) dbo.get("_ID");
System.out.println(id);
}
Haven't really tested this. But just give it a try. Should work.

Trimming double quotes of a string which is saved as a value in mongodb java driver

I have something like this written using mongodb driver for java:
doc = new BasicDBObject("Physicalentity", "Pressure").
append("Sensor", "Tinkerforge").
append("Unit", "Lux").
append("loc", Location).
append("value", pressure).
append("time", time).
append("date", date);
pre_collection.insert(doc);
As you can see in the above code, I do not insert double quote for attribute loc and the location is defined as follow:
String longtitude = "8.9043";
String latitude = "52.0777";
String Location = "["+longtitude+","+latitude+"]";
Now In the database it is stored as:
{ "_id" : { "$oid" : "5367da1211f6e33b6eba4a9f"} , "Physicalentity" : "Pressure" , "Sensor" : "Tinkerforge" , "Unit" : "Lux" , "loc" : "[8.9043,52.0777]" , "value" : "Air Pressure: 1008.177 mbar" , "time" : "20.36.02" , "date" : "05.05.2014"}
but as you can see the attribute loc is stored with double quotes "[8.9043,52.0777]" but I want them to be saved without the double quotes or if possible like this: “loc:[51,-114]”
I would really appreciate a help here.
Thanks a lot in advance.
When writing that value, use a BasicDBList for your two coordinates. This will cause them to be saved out as an array in your document.
From the documentation:
BasicDBObject doc = new BasicDBObject("Physicalentity", "Pressure").
append("Sensor", "Tinkerforge").
append("Unit", "Lux").
append("loc", new BasicDBObject("longtitude", 203).append("latitude", 102));
append("value", pressure).
append("time", time).
append("date", date);
pre_collection.insert(doc);
But maybe you can do a little trick and remove with code the first and the last quotes like this:
String word="[wdsd34svdf]";
System.out.println(word.substring(1, word.length()-1));
I hope it helps :)

MongoDB - How to find and append / find and upsert both document and fields

In Mongo, is there a built-in way to update a document and instead of replacing all contents of the query document, to update those nodes which are the same and append those which do not exist in the original document.
For example, imagine I insert the following document into my collection:
{
"name" : "Goku",
"level" : 9000
}
Now, at some later point, I wish to update my existing document with the following document I received:
{
"name" : "Goku",
"son" : "Gohan"
}
Ideally, I would like a way to perform an update and produce the following document:
{
"name" : "Goku",
"level" : 9000,
"son" : "Gohan"
}
The standard case is to overwrite the existing document with the new document (as it should be). However, is there a built-in or clever way to achieve the result above without first finding the first document, appending onto it, and then performing an update?
Thanks.
-- EDIT --
#pennstatephil has the correct answer below. Just in case anyone's is helped by this, here's an implementation of this example in Java as of driver version 2.12.0:
String json = "{'name' : 'Goku', 'level' : 9000 }";
DBObject document = (DBObject) JSON.parse(json);
BasicDBObject update = new BasicDBObject("$set", document);
BasicDBObject query = new BasicDBObject().append("name", document.get("name"));
collection.findAndModify(query, null, null, false, update, false, true);
json = "{'name' : 'Goku', 'son' : 'Gohan'}";
document = (DBObject) JSON.parse(json);
update = new BasicDBObject("$set", document);
query = new BasicDBObject().append("name", document.get("name"));
collection.findAndModify(query, null, null, false, update, false, true);
I believe findAndModify and $set (on the update clause) is what you're looking for.

MongoDB find query

I use mongoDB to collect comments inside a collection comments
I use this java programme to create them
...
BasicDBObject comment=new BasicDBObject();
BasicDBObject auteur=new BasicDBObject();
auteur.put("id", id);
auteur.put("login", login);
auteur.put("contact",false);
comment.put("auteur",auteur);
comment.put("texte",texte);
...
When i try to find the comment using the field texte it works:
db.comments.find({"texte":"my name is user1"})
{
"_id" : ObjectId("5341395ae4b082f5895d5967"),
"auteur" : { "id" : 1, "login" : "user1", "contact" : false },
"texte" : "my name is user1"
}
However my aim is to find them by using the the field id of auteur.
I tried
db.comments.find({"auteur":{"id":1}})
but it returns nothing...
I'm really lost. Thanks!!
You would use the Dot Notation to access the id of the sub document auteur:
db.comments.find({"auteur.id": 1});
The dot notation can also be used to access an element of an array by the zero-based index position:
db.things.find({"an_array_name.15": "a text to search..."});
Regards.
Mohamed.

Categories

Resources