How to create MongoID in android code? - java

I am developing app with mongoDB support in android.
I want to create MongoID from java code and send it to my server.
Here is my code
I want to create this json
{
"_id" : ObjectId("59b7bcdf92e706382b00009f"),
"user_id" : "6bb82a99-bccd-4868-a799-55e7d28f969c",
"is_active" : false,
"_slugs" : [
"aaa"
],
"facility_name" : "aaa",
"industry_id" : 1,
"old_industry_id" : 1,
"established_date" : "1994-06-01",
"summary" : "this is test",
"facility_website" : "www.xxx.com",
"contact" : {
"_id" : ObjectId("4637gdff92jhsgd378364y"),
"info_type" : "PROFILE_INFO",
"name" : "xxxxxxxxxx",
"mobileNumber" : "xxxxxxxxx",
"email" : "xxxxxxx#gmail.com",
"shown_on_profile" : true
}}
But I am getting this Json from my java code.
{
"_id" : ObjectId("59b7bcdf92e706382b00009f"),
"user_id" : "6bb82a99-bccd-4868-a799-55e7d28f969c",
"is_active" : false,
"_slugs" : [
"aaa"
],
"facility_name" : "aaa",
"industry_id" : 1,
"old_industry_id" : 1,
"established_date" : "1994-06-01",
"summary" : "this is test",
"facility_website" : "www.xxx.com",
"contact" : {
"_id" : "{}",
"info_type" : "PROFILE_INFO",
"name" : "xxxxxxxxxx",
"mobileNumber" : "xxxxxxxxx",
"email" : "xxxxxxx#gmail.com",
"shown_on_profile" : true
}}
Problem is in "contact" object
Here is my java code
String _id = new JsonObject().toString(); // this is Gson.JsonObject() object
JSONObject contact = new JSONObject();
contact.put("_id", _id);
contact.put("info_type", "PROFILE_INFO");
contact.put("name", "User-1");
contact.put("mobileNumber", "xxxxxxxxxx");
contact.put("email", "xxxxx#gmail.com");
contact.put("shown_on_profile", true);

The MongoID is automatically generated by the server. What you need to do, is to send your contact without the MongoID. The server will insert the data in the database and return the MongoID of this element just created, and you can return the entire contact or just the MongoID to your Android app to use it.

As said by #fandro i have solved my issue.
Server gives me mongoDB data like this
{"_id":{"$id":"59b7bcdf92e706382b00009f"}}
I can access this data using this code,
Here is my android Code
ID = jsonData.getJSONObject("_id).getString("$id");
For generating new ID i have created empty JSONObject in android and passed to my server.
_id = new JSONObject().put("$id", "");
On my server, i check id and if it is empty then i generate new MongoID form this code,
<?php
$_id = $_POST['_id'];
if ($_id['$id'] == "")
$_id = new MongoID();
?>

Related

Mongodb Java Driver Insert Array to Collection

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;

Retrieve all the documents matching the criteria in an array elements which is a subdocument

{
"_id" : ObjectId("577b54816081dd32cd3e2d60"),
"user" : ObjectId("577b54816081dd32cd3e2d5e"),
"journals" : [
{
"title" : "Journal Title2",
"desc" : "desx2",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:32:45.404Z"),
"deleteFl" : true,
"_id" : ObjectId("577b548d6081dd32cd3e2d64")
},
{
"title" : "Journal Title3",
"desc" : "desx3",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:49:00.156Z"),
"deleteFl" : false,
"_id" : ObjectId("577b585c6081dd32cd3e2d6d")
},
{
"title" : "Journal Title4",
"desc" : "desx4",
"feeling" : 3,
"date" : ISODate("2016-07-05T06:49:06.700Z"),
"deleteFl" : false,
"_id" : ObjectId("577b58626081dd32cd3e2d70")
}
]
}
Above is my document structure
now, I need all the journal documents whose deleteFl = false.
I tried in this way using Java Mongo driver
getDatabase().getCollection("journals").find(and(eq("user", user), eq("journals.deleteFl", false)));
but still it gives me back all the documents including "deleteFl": true. any help here ?
Actually, your query returns 1 document, because the data is inside 1 document. What you want is to limit the returning fields of a document (limit subdocuments).
Note: You can do that using elemMatch in the projection, to limit the fields returned by the query. But elemMatch will return just one subdocument. (I posted a deleted wrong answer using elemMatch)
When you want all subdocuments and only specific subdocuments from inside an array, you need to use the aggregation pipeline.
Here is a tested code that does what you want (just change DB and colelction name):
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection collection = db.getCollection("test");
Iterable<Document> output = collection.aggregate(asList(
new BasicDBObject("$unwind", "$journals"),
new BasicDBObject("$match", new BasicDBObject("journals.deleteFl", false))
));
for (Document dbObject : output)
{
System.out.println(dbObject);
}

How to find user on the basis of its ID in mongodb using java criteria query?

Friends I have come across a problem of finding the user on the basis of user id . My user id is in long form and I am using this code to fetch user
Query query = new Query(Criteria.where("user.$id").is(userId));
User user = mongoTemplate.findOne(query, User.class);
And I am using counter to set id while saving user so in DB my collection is in this form
db.users.find().pretty()
{
"_id" : NumberLong(1),
"_class" : "com.domain.user.User",
"age" : 20,
"username" : "abc#gmail.com",
"roles" : [
"ROLE_USER"
],
"firstName" : "abc",
"lastName" : "xyz",
"email" : "abc#gmail.com",
"gender" : "male",
"isAccountLocked" : false,
"prefAgeFrom" : 0,
"prefAgeTo" : 0,
"aboutMe" : "I like to meet new people",
"notificationNewMatch" : true,
"notificationMessage" : true,
"updatedDate" : ISODate("2015-06-08T07:30:45.878Z")
}
So on the basis of id which is stored in NumberLong(1) form I want to get user of id = 1.
In present scenerio, I am getting user null on the basis of id mentioned above.
My main requirement is that I want to fetch token on the basis of user. My token stored in DB in this form
db.authenticationToken.find().pretty()
{
"_id" : NumberLong(4),
"_class" : "com.domain.user.AuthenticationToken",
"token" : "6db92ee4-2c23-42ee-985e-08af8e3d4f58",
"updatedDate" : ISODate("2015-06-10T04:47:34.434Z"),
"user" : DBRef("users", NumberLong(1))
}
Can anyone help me!
Doing some research over my issue i finally got the solution , we can find the token on the basis of user id like this
Query query = new Query(Criteria.where("user").is(userId))
mongoTemplate.findOne(query,AuthenticationToken.class);

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 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.

Categories