Java equivalent of scala query in mongodb - java

What is the equivalent cde in Java:
var result = collectionName.findOne()
println(result.get("name").toString)
To elaborate, This is my sample db:
{ "_id" : ObjectId("4ca039f7a5b75ab98a44b149"), "name" : "kaustubh", "country" : "india" }
{ "_id" : ObjectId("4ca03a85a12344a5e47bcc5c"), "name" : "rahul", "country" : "pakistan" }
{ "_id" : ObjectId("4ca03a9ea12344a5e47bcc5d"), "name" : "swapnil", "country" : "lanka" }
{ "_id" : ObjectId("4ca03b19a12344a5e47bcc5e"), "name" : "sagar", "country" : "nepal" }
i am running the following query on it:
query.put("country", "india");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
that prints:
{ "_id" : { "$oid" : "4ca04b6b37a85ab92557218a"} , "name" : "kaustubh" , "country" : "india"}
as many times as the pair exists in the collection.
how do I formulate a query to get all the names, once and get the count for them.I read the docs, and didnt stumble upon any way to do it.

Try this
query.put("name", "kaustubh");
DBObject myDoc = collection.findOne(query);
System.out.println(myDoc);

Related

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.

How to construct basicdbobject query to delete deep array documnet?

I am having mongo document as below
"_id" : ObjectId("5072b33aa4e8dd3e359b8e94"),
"menus" : {
"5072b8dda4e8dd3e359b8ea8" :
{
"_id" : ObjectId("5072b8dda4e8dd3e359b8ea8"),
"description" : "hfghfgh",
"MenuItems" :
[
{
"name" : "dfgdfg",
"description" : "dgdfgd",
"_id" : ObjectId("5072b91ba4e8dd3e359b8eaa")
},
{
"name" : "fgdfgdf",
"description" : "gdfgg",
"_id" : ObjectId("5072bb92a4e8204e51de1084")
}
]
}
}
Actually i had tried to delete the following object in the menuItems
{
"name" : "fgdfgdf",
"description" : "gdfgg",
"_id" : ObjectId("5072bb92a4e8204e51de1084")
}
My query as follows but its not working.
BasicDBObject query=new BasicDBObject("_id",objectId("...");
BasicDBObject document = new BasicDBObject("menus.5072b8dda4e8dd3e359b8ea8.menuItems.$._id", ObjectId("5072bb92a4e8204e51de1084") );
BasicDBObject updateOps=new BasicDBObject("$pull", document);
I am having id of menuItems "_id" : ObjectId("5072bb92a4e8204e51de1084") , id of menus "_id" : ObjectId("5072b8dda4e8dd3e359b8ea8") and id of top level document "_id" : ObjectId("5072b33aa4e8dd3e359b8e94"),
BasicDBObject query=new BasicDBObject("_id",new ObjectId(".....");
BasicDBObject document = new BasicDBObject("menus.5072b8dda4e8dd3e359b8ea8.menuItems",
new BasicDBObject("_id":ObjectId("5072bb92a4e8204e51de1084") );
BasicDBObject updateOps=new BasicDBObject("$pull", document);
db.collection.update(query,updateOps);

How to construct query to update nested array document in mongo?

I am having following document in mongo,
{
"_id" : ObjectId("506e9e54a4e8f51423679428"),
"description" : "ffffffffffffffff",
"menus" : [
{
"_id" : ObjectId("506e9e5aa4e8f51423679429"),
"description" : "ffffffffffffffffffff",
"items" : [
{
"name" : "xcvxc",
"description" : "vxvxcvxc",
"text" : "vxcvxcvx",
"menuKey" : "0",
"onSelect" : "1",
"_id" : ObjectId("506e9f07a4e8f5142367942f")
} ,
{
"name" : "abcd",
"description" : "qqq",
"text" : "qqq",
"menuKey" : "0",
"onSelect" : "3",
"_id" : ObjectId("507e9f07a4e8f5142367942f")
}
]
},
{
"_id" : ObjectId("506e9e5aa4e8f51423679429"),
"description" : "rrrrr",
"items" : [ {
"name" : "xcc",
"description" : "vx",
"text" : "vxc",
"menuKey" : "0",
"onSelect" : "2",
"_id" : ObjectId("506e9f07a4e8f5142367942f")
} ]
}
]
}
Now , i want to update the following document :
{
"name" : "abcd",
"description" : "qqq",
"text" : "qqq",
"menuKey" : "0",
"onSelect" : "3",
"_id" : ObjectId("507e9f07a4e8f5142367942f")
}
I am having main documnet id: "_id" : ObjectId("506e9e54a4e8f51423679428") and menus id
"_id" : ObjectId("506e9e54a4e8f51423679428") as well as items id "_id" : ObjectId("507e9f07a4e8f5142367942f") which is to be updated.
I have tried using the following query:
db.collection.update({ "_id" : { "$oid" : "506e9e54a4e8f51423679428"} , "menus._id" : { "$oid" : "506e9e5aa4e8f51423679429"}},{ "$set" : { "menus.$.items" : { "_id" : { "$oid" : "506e9f07a4e8f5142367942f"}} , "menus.$.items.$.name" : "xcvxc66666", ...}},false,false);
but its not working...
The positional operator does not work on the number of levels you are trying to get it to work on ( https://jira.mongodb.org/browse/SERVER-831?focusedCommentId=22438&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel ) with menus.$.items.$.name and even if it did MongoDB query parser would have no idea what the other $ is from the find of the update.
You will need to pull out the items from the schema, update that seprately and then update the root document.
One good way of judging when queries should be done separately is to think that each menu sounds like a separate entity (or table in a relational database) as such you should probably work on updating those entites (or tables in a relational model) separately to the parent entity (table).
So first you would get out the main root document. Scroll across it's menus in client side and then $set that particular menu to the entire item you build on client side.
Edit
The way I imagine this work client side is (in pseudo code since my Java is a little rusty) by first getting that document in an active record fashion:
doc = db.col.find({ "_id" : { "$oid" : "506e9e54a4e8f51423679428"} ,
"menus._id" : { "$oid" : "506e9e5aa4e8f51423679429"}});
Then you would iterate through the document assigning your values:
foreach(doc.menus as menu_key => menu){
foreach(menu['items'] as key => item){
if(item._id == { "$oid" : "506e9f07a4e8f5142367942f"}){
doc.menus[menu_key][key][name] = "xcvxc66666"
}
}
}
And then simple save the doc after all changes are commited:
db.col.save(doc);
This is of course just one way of doing it and this way uses the activen record paradigm which I personally like. In this idea you would combine the find with everything else you need to modify on the document, building it up client side and then sending it all down as one single query to your DB.

Polishing a mongodb query

This is my current query: Using Java+mongoDB
{
BasicDBObject select = new BasicDBObject();
select.put("info.name.fn", 1);
DBCursor cursor = collection.find(new BasicDBObject(), select);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
It gives an output as:
{ "_id" : { "$oid" : "123"} , "info" : { "name" : { "fn" : "foo"}}}
{ "_id" : { "$oid" : "123"} , "info" : { "name" : { "fn" : "bar"}}}
{ "_id" : { "$oid" : "123"} , "info" : { "name" : { "fn" : "baz"}}}
_ids changed to accommodate the output. My question is, what query do I give to get the output as:
foo
bar
baz
Is it even possible? Or does every query always return it in the above format? I cant run a distinct() because there are duplicate names.
Thanks.
The minimal query result you can get is the one you show above.
You do not have to print all of that, though.
System.out.println(cursor.next().get("info").get("name").get("fn"));

Categories