Generated ObjectId for MongoDB - java

I'd need to generate ObjectId for my entities before I save them to MongoDB. I generate it simply with new org.bson.types.ObjectId(). It creates an object _id which is a quaternion of _time, _machine, _inc and _new. The value of _id itself looks like a normal MongoDB _id. Nevertheless after transforming to JSON and sending it to database, it's saved as an array of four elements. Is there any way how to make it to look like ObjectId generated by MongoDB - "_id" : ObjectId("54edaa41ca190ebda00a2abd") without any text preoprocessing?

This simple Java program works.
MongoClient mongoClient = new MongoClient();
ObjectId objectId = ObjectId.get();
DB test1 = mongoClient.getDB("test1");
BasicDBObject dbObject = new BasicDBObject("_id",objectId)
.append("key", "value");
test1.getCollection("test").insert(dbObject);
Now query with Shell, ObjectId is saved correctly.
> use test1
switched to db test1
> db.test.find()
{ "_id" : ObjectId("55520a15b8a0e51f45921946"), "key" : "value" }

Related

How to search a document and remove field from it in mongodb using java?

I have a device collection.
{
"_id" : "10-100-5675234",
"_type" : "Device",
"alias" : "new Alias name",
"claimCode" : "FG755DF8N",
"hardwareId" : "SERAIL02",
"isClaimed" : "true",
"model" : "VMB3010",
"userId" : "5514f428c7b93d48007ac6fd"
}
I want to search document by _id and then update it after removing a field userId from the result document. I am trying different ways but none of them is working. Please help me.
You can remove a field using $unset with mongo-java driver in this way:
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("testDB");
DBCollection collection = db.getCollection("collection");
DBObject query = new BasicDBObject("_id", "10-100-5675234");
DBObject update = new BasicDBObject();
update.put("$unset", new BasicDBObject("userId",""));
WriteResult result = collection.update(query, update);
mongo.close();
The easiest way is to use the functionality in the java driver:
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId("10-100-5675234")));
Update update = new Update();
update.unset("userId"); //the fields you want to remove
update.set("putInYourFieldHere", "putInYourValueHere"); //the fields you want to add
mongoTemplate.updateFirst(query, update, Device.class);
The above code assumes that your "_id" is your mongodb normal "_id" which means that the variable you are looking for must be encased in the new ObjectId().
Long time since this post was opened, but might be useful for someone in the future.
device.updateMany(eq("_id", "whatever"), unset("userId"));
An ugly way is to replace the old version with the new version of you document (no userid).
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("_type", "Device");
newDocument.put("alias", "new Alias name");
// ...
BasicDBObject searchQuery = new BasicDBObject().append("_id", "10-100-5675234");
collection.update(searchQuery, newDocument);
The MongoDB documentation provides a clear answer to this question: use the $unset update operator.

Filter mongodb cursor in a subfield of document

I trying to perform a query in my mongo database using java code. I want to filter the result of the query using cursor. Basically I want to filter the cursor results two times. My query return some documents, and I want to filter them based on a field of document and a sub-field of the first field. For example:
DBCursor cursor = coll.find(query);
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
System.out.println(obj.getString("images"));
}
Return the image field from all quered documents. What should I do if I want to return the field "link" which is a subfield of field "images"? I tried obj.getString("images").getString("link"), however it doesn't work. Images is an array with three fields the first one is the filed "link". When the above return is the following: [ { "link" : "http://distilleryimage1.ak.instagram.com/fc7c5_7.jpg" , "phash" : "01000010101000101010111101" , "persons" : 1}] . I want to return just the first field link.
Just get images as ArrayList:
ArrayList<BasicDBObject> images = (ArrayList<BasicDBObject>)obj.get("images");
for(BasicDBObject image: images)
{
String link = image.getString("link");
.......
}

Define and Retrieve key-values in MongoDB

I want to define a document in MongoDB in order to keep a list of key-value pairs in addition to some more information . I need to query on keys and extract just values , not whole the document. Let’s say it looks like:
{ title :” Do not stop me now”
Artist: “Queen”
Info :{
Metadata: [
{key: “genre”, value: “Rock” },
{key: “bps”, value: 120}
]
}
}
I selected this format based on http://java.dzone.com/articles/indexing-schemaless-documents
I want to query like select “genre” from song where artist is “Queen”
My current code is:
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("key","genre");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
BasicDBObject query = new BasicDBObject();
query.put("info.Metadata", up);
query.put(“Artist”,”Queen”);
BasicDBObject fields = new BasicDBObject("info.Metadata.$",1).append("_id", false);
DBObject object =collection.findOne(query,fields);
I tried to extract value like:
System.out.println( (((BasicBSONList) ((BasicBSONObject) object.get("info")).get("Metadata")).get("value")).toString());
But I cannot get access to "value"
How I can solve it?
The positional operator return an array of one element. So, what you are converting to string is an array and of course you will get a kind of java id.
Cast it to array and get its first element

How to insert multiple documents at once in MongoDB through Java

I am using MongoDB in my application and was needed to insert multiple documents inside a MongoDB collection .
The version I am using is of 1.6
I saw an example here
http://docs.mongodb.org/manual/core/create/
in the
Bulk Insert Multiple Documents Section
Where the author was passing an array to do this .
When I tried the same , but why it isn't allowing , and please tell me how can I insert multiple documents at once ??
package com;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class App {
public static void main(String[] args) {
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("at");
DBCollection collection = db.getCollection("people");
/*
* BasicDBObject document = new BasicDBObject();
* document.put("name", "mkyong"); document.put("age", 30);
* document.put("createdDate", new Date()); table.insert(document);
*/
String[] myStringArray = new String[] { "a", "b", "c" };
collection.insert(myStringArray); // Compilation error at this line saying that "The method insert(DBObject...) in the type DBCollection is not applicable for the arguments (String[])"
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please let me know what is the way so that I can insert multiple documents at once through java .
DBCollection.insert accepts a parameter of type DBObject, List<DBObject> or an array of DBObjects for inserting multiple documents at once. You are passing in a string array.
You must manually populate documents(DBObjects), insert them to a List<DBObject> or an array of DBObjects and eventually insert them.
DBObject document1 = new BasicDBObject();
document1.put("name", "Kiran");
document1.put("age", 20);
DBObject document2 = new BasicDBObject();
document2.put("name", "John");
List<DBObject> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insert(documents);
The above snippet is essentially the same as the command you would issue in the MongoDB shell:
db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]);
Before 3.0, you can use below code in Java
DB db = mongoClient.getDB("yourDB");
DBCollection coll = db.getCollection("yourCollection");
BulkWriteOperation builder = coll.initializeUnorderedBulkOperation();
for(DBObject doc :yourList)
{
builder.insert(doc);
}
BulkWriteResult result = builder.execute();
return result.isAcknowledged();
If you are using mongodb version 3.0 , you can use
MongoDatabase database = mongoClient.getDatabase("yourDB");
MongoCollection<Document> collection = database.getCollection("yourCollection");
collection.insertMany(yourDocumentList);
As of MongoDB 2.6 and 2.12 version of the driver you can also now do a bulk insert operation. In Java you could use the BulkWriteOperation. An example use of this could be:
DBCollection coll = db.getCollection("user");
BulkWriteOperation bulk = coll.initializeUnorderedBulkOperation();
bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));
bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));
bulk.execute();
Creating Documents
There're two principal commands for creating documents in MongoDB:
insertOne()
insertMany()
There're other ways as well such as Update commands. We call these operations, upserts. Upserts occurs when there're no documents that match the selector used to identify documents.
Although MongoDB inserts ID by it's own, We can manually insert custom IDs as well by specifying _id parameter in the insert...() functions.
To insert multiple documents we can use insertMany() - which takes an array of documents as parameter. When executed, it returns multiple ids for each document in the array. To drop the collection, use drop() command. Sometimes, when doing bulk inserts - we may insert duplicate values. Specifically, if we try to insert duplicate _ids, we'll get the duplicate key error:
db.startup.insertMany(
[
{_id:"id1", name:"Uber"},
{_id:"id2", name:"Airbnb"},
{_id:"id1", name:"Uber"},
]
);
MongoDB stops inserting operation, if it encounters an error, to supress that - we can supply ordered:false parameter. Ex:
db.startup.insertMany(
[
{_id:"id1", name:"Uber"},
{_id:"id2", name:"Airbnb"},
{_id:"id1", name:"Airbnb"},
],
{ordered: false}
);
Your insert record format like in MongoDB that query retire from any source
EG.
{
"_id" : 1,
"name" : a
}
{
"_id" : 2,
"name" : b,
}
it is mongodb 3.0
FindIterable<Document> resulutlist = collection.find(query);
List docList = new ArrayList();
for (Document document : resulutlist) {
docList.add(document);
}
if(!docList.isEmpty()){
collectionCube.insertMany(docList);
}

How to get column names from HQL query&result to json with Key as columns

How to convert hql query result directly to Json.I tried this one
Query query=session.createQuery(SQLUtilsConstants.fQuery);
query.setParameter(StringConstants.TRPID, trId);
List list=query.list();
gson = new Gson();
String jsonStudents = gson.toJson(list);
System.out.println("jsonStudents = " + jsonStudents);
When i converted.I get a json with list of values without properties.Query result contains data from multiple table .I want to generate result with properties as key and value as output.If query contains customerid and customername then i need a result like this.
[{"customerid" : "abc", "customername" : "rose"}]
But using above code i getting like this..
[{"abc", "rose"}]
How can i do this???
You should create a Map, how ever you want it. then parse the map into json.
Map<String,WhatEver> newMap = new HashMap<String,WhatEver>();
foreach(WhatEver item: list){
//create your map how ever you like it to be
}
String jsonStudents = gson.toJson(newMap);

Categories

Resources