MongoDB find query - java

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.

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.

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.

Unable to update Inner Arraylist object using Mongodb Java Driver

I have below document structure in mongodb database:
{
"_id" : ObjectId("52ec7b43e4b048cd48499b35"),
"eidlist" : [
{
"eid" : "64286",
"dst" : NumberLong(21044),
"score" : 0
},
{
"eid" : "65077",
"dst" : NumberLong(21044),
"score" : 0
}
],
"src" : NumberLong(21047)
}
I would like to update score field of first object using Java-mongodb driver:
I tried following code but it is not working :( :
DBObject update_query=new BasicDBObject("src", key).append("eidlist.eid", e.getEdgeid());
DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.score",100));
coll.update(update_query, data);
Please help me to solve this problem..I have checked all the parameter which I have passed to update function.I think something wrong with the update logic :(
You were close. You omiited the positional operator from the update. Edit your code as shown.
DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.$.score",100));
Solution for this problem is:
DBObject data=new BasicDBObject("$set",new BasicDBObject("eidlist.$.score",""+100));
Ensure data type of every field used in the update query.It should be compatible with what we have stored in the mongodb :)

Insert a document in a document

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

Categories

Resources