Mongodb Java Driver Insert Array to Collection - java

I have a little problem while inserting array values to existing collection in MongoDB. I have a collection as below ;
{ "_id" : "1", "username" : "", "password" : "!", "firm" : "SpringSource", "roles" : [ "admin", "client" ], "items" : [ { "_id" : "1b7cb58b-dc5b-4d27-9402-d43d3844d11d", "id" : 1, "title" : "Coffee", "price" : "12", "category" : "Coffee", "images" : "Obj1", "description" : "Coffee" } ], "latitude" : "39.877619", "longitude" : "32.682537" }
What I need is changing "images" tag's value to array value as below;
"items" : [ { "_id" : "1b7cb58b-dc5b-4d27-9402-d43d3844d11d", "id" : 1, "title" : "Coffee", "price" : "12", "category" : "Coffee", "images" : ["Obj1","Obj2"], "description" : "Coffee" } ], "latitude" : "39.877619", "longitude" : "32.682537" }
I have Items class in Java and objects of this class inserted to MongoDB as below;
Item item= new Item(id,title,price,category,image,description);
//String all=item.toString();
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(item);
Document doc = Document.parse( json.toString() );
db.getCollection("users").updateOne(new Document("username",uname1),
new Document("$push", new Document("items", doc)));
It works as expected but as I indicated above I need to store images as an array. I tried something below;
List<String> topics = new ArrayList<String>();
topics.add("Obj1");
topics.add("Obj2");
col.findOneAndUpdate(Filters.eq("_id", new. ObjectId("58b1404d002d2b1a481b8ddf")), Updates.pushEach("images", topics));
But it did not work. I have searched a lot there are many examples but I could not figure out how to do. Any recommendations?
Thanx

The simplest idea is to change Item class and instead of
String images;
change to
List<String> images;

Related

How do I get values of same key from all documents in MongoDB using Java?

I am new in working on mongodb. Here is my Mongodb documents I only want the name values.
{
"_id" : ObjectId("5da527f784a58d78fcd0b177"),
"name" : "Jabed",
"email" : "jabed#gmail.com",
"Sex" : "male",
"age" : "19",
"address" : "Kochukhet, Dhaka",
"Contct" : "01797259329"
}
{
"_id" : ObjectId("5da6f415f2bdee4b90cf41d0"),
"name" : "Bulbul Gulzer Deb",
"email" : "gulzer.deb#gmail.com",
"Sex" : "male",
"age" : "19",
"address" : "Narinda, Dhaka",
"Contct" : "01756223666"
}
{
"_id" : ObjectId("5dd771907607c3e12d9183d7"),
"name" : "Aniruddha Dey",
"email" : "aniruddha.dey#gmail.com",
"Sex" : "male",
"age" : "14",
"address" : "Narinda, Dhaka",
"Contct" : "01745706020"
}
Expected output will be
Jabed
Bulbul Gulzer Deb
Aniruddha Dey
Use the projection:
db.yourdocument.find( {}, { name: 1, _id: 0 } )
More control over projected fields can be found here

How do insert an inner document in an existing document in mongodb in java?

I have a document in collection names user which is as follows:
{
"_id" : "abc#gmail.com",
"Password" : "xyz",
"first_name" : "ABC",
"last_name" : "PQR",
}
I want to insert an inner document job_desc having some entries like job, place, salary
after modifying the user document becomes like this
{
"_id" : "abc#gmail.com",
"Password" : "xyz",
"first_name" : "ABC",
"last_name" : "PQR",
"doc" : { "job_desc" : "Design Engineer", "place" : "Bengaluru", "salary" : 40K USD }
}
I tried using append but it is for new document entry and then using $set but it is used for replacing the specified value. How do I meet my requirement?
Insert a new nested object using Java
BasicDBObject doc = new BasicDBObject("doc",new BasicDBObject("job","Design Engineer").append("place","Bengaluru").append("salary", "40K USD"));
BasicDBObject query = new BasicDBObject();
query.put("_id","abc#gmail.com");
BasicDBObject set = new BasicDBObject("$set", doc);
collection.update(query, set);
// result doc
{
"_id" : "abc#gmail.com",
"Password" : "xyz",
"first_name" : "ABC",
"last_name" : "PQR",
"doc" : {
"job" : "Design Engineer",
"place" : "Bengaluru",
"salary" : "40K USD",
}
}
In mongo console use this code for adding just one value to your existing nested doc(or event non existing):
db.collection.update({"_id":"abc#gmail.com"}, {$set : {'doc.newField' : 'newValue'}})
the result would be:
// modified doc
{
"_id" : "abc#gmail.com",
"Password" : "xyz",
"first_name" : "ABC",
"last_name" : "PQR",
"doc" : {
"job" : "Design Engineer",
"place" : "Bengaluru",
"salary" : 500,
"newField" : "newValue"
}
}

how to create mongoDB objectid in java

Refering to post How to add an array to a MongoDB document using Java?
I have created a mongo schema using java
it has sub elements, I am getting _id for main document
I would like to get _id in sub elements also here output looks (I have marked the portion where I need _id) b.party.find().pretty();
{
"_id" : ObjectId("5399aba6e4b0ae375bfdca88"),
"addressDetails" : [
{
// _id here
"locationName" : "Office",
"phones" : [
{ // _id here
"name" : "Tel1",
"value" : "95253-"
},
{ // _id here
"name" : "Tel2",
"value" : "95253-"
},
{ // _id here
"name" : "Tel3",
"value" : "95253-"
},
{ // _id here
"name" : "Fax1",
"value" : "0253-"
}
],
"address" : "A-3,MIDCA-3,MIDC",
"defaultBillAddrerss" : "",
"pincode" : "422 010",
"city" : null,
"state" : "1",
"country" : ""
},
{ // _id here
"locationName" : "Factory",
"phones" : [
{ // _id here
"name" : "Tel1",
"value" : "0253-"
},
{ // _id here
"name" : "Tel2",
"value" : "0253-"
},
{ // _id here
"name" : "Tel3",
"value" : "0253-"
},
{ // _id here
"name" : "Fax1",
"value" : "0253-"
}
],
"address" : "A-3 INDUSTRIAL AREA,",
"defaultBillAddrerss" : "",
"pincode" : "422 010",
"city" : null,
"state" : "1",
"country" : ""
}
],
"crLimit" : "0.0",
"crPeriod" : "",
"name" : "CROMPTON GREAVES "
}
Java code to create is similar to How to add an array to a MongoDB document using Java?
Is there any code to create ObjectId("") programmatically in java?
To create objectId programmatically, use the following syntax
import org.bson.types.ObjectId;
ObjectId id1 = new ObjectId();
ObjectId id2 = ObjectId.get();
// In case you want to mention the parent ID itself,
ObjectId id3 = new ObjectId("5399aba6e4b0ae375bfdca88");
To create objectId programmatically, use the following syntax
Map<String,String> objectId = new HashMap<String,String>();
objectId.put("$oid","5399aba6e4b0ae375bfdca88");
Then insert into mongodb.

MongoDB Query with Java

I have the following database structure in MongoDB (see below) and I want to do a search query on the fields 'name'
Database structure:
{
"_id" : ObjectId("505ad9a7ed5022cbe1f3dc2e"),
"id" : "10",
"description" : "",
"members" : [{
"id" : "1",
"name" : "Jack"
}, {
"id" : "2",
"name" : "Mike"
}, {
"id" : "3",
"name" : "Laura"
}, {
"id" : "4",
"name" : "Sara"
}, {
"id" : "240",
"name" : "Ronald"
}],
"status" : "active"
},
{
"_id" : ObjectId("5059c214707747cbc5819f6f"),
"id" : "12",
"description" : "",
"members" : [{
"id" : "19",
"name" : "Geoff"
}, {
"id" : "21",
"name" : "Andrew"
}, {
"id" : "23",
"name" : "Rachel"
}, {
"id" : "25",
"name" : "Susan"
}],
"status" : "active"
},
I have the following code will do a search on the field 'description' or 'status'. DBCollection collection = database.getCollection("members");
BasicDBObject or1 = new BasicDBObject();
or1.put("description", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
BasicDBObject or2 = new BasicDBObject();
or2.put("status", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
BasicDBList or = new BasicDBList();
or.add(or1);
or.add(or2);
BasicDBObject query = new BasicDBObject();
query.put("$or", or);
BasicDBObject select = new BasicDBObject();
select.put("description", 1);
select.put("status", 1);
DBCollection collection = collection.find(query, select);
Question is, how would I do an OR search on the field 'members.name' ? So if I would search for the name or text 'Laura' that the document/record with id 10 will be in the result set.
Would I have to loop through all the results or something like that?
Thanks for any help or suggestions!
If I understand the question correctly, it is really a question about how to search a single field inside of an array. Use the full path to the field in question. In this case, it is "members.name".
Now, if you want to AND the members names together to find records that contain two specific members, just put the individual queries into a BasicDBList as you did with OR and then AND them together. If you want to include the other OR query list, just toss that query object (used in the code sample above) into that BasicDBList to be included with the AND.

How to update embedded document in mongo?

I am having the following document in the mongo db.
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" : [
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
{
"name" : "rtytry",
"description" : "gffhf",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98281f00")
}],
"select":"ffdfgd"
}
I want to do automatic update of menus
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
}
I have tried using the following code:
BasicDBObject query = new BasicDBObject("_id", new ObjectId("50656f33a4e82d3f98291eff"));
BasicDBObject update = new BasicDBObject("_id", ObjectId("50656f3ca4e82d3f98291f00"));
BasicDBObject updateCommand = new BasicDBObject("$set", new BasicDBObject("menus", update));
collection.update(query, updateCommand);
The result i got is
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" :
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
"select":"ffdfgd"
}
but i want to update in the same embedded document.
Any one guide me ....Thanks in advance
Ok After having to read this a couple of times (English...) I think I understand now.
You want to upto the subdocument with the _id 50656f3ca4e82d3f98291f00 with:
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
}
First problem you have is that your code merely sets menus field to this object. What you need is the postional operator. So you need to do a dot notation find (warning my Java is a little rusty):
query.append("menus._id", new ObjectId("50656f3ca4e82d3f98291f00"));
And then use that positional operator to update in position:
BasicDBObject update_document = new BasicDBObject("menus.$.name", my_new_subdocument.name);
update_document.append("menus.$.description", my_new_subdocument.description);
// All the other fields
BasicDBObject updateCommand = new BasicDBObject("$set", update_document);
Hopefully that should do the trick.

Categories