How to get the _id of one document MongoDB Java - java

I'm using MongoDB and Java-driver.
I need to insert a document into MongoDB and retrieve the _id of this document. The insert method return a [WriteResult][1].
I don't know how I have to use the WriteResult object to retrieve the _id, because I try to do this:
public void insertDocument(BasicDBObject fact){
DBCollection coll = this.getCollection("facts");
WriteResult result = coll.insert(fact);
String id = (String) result.getField("_id");
System.out.println("--------------------------->"+id);
}
And I have a null String in the println.
My question is how I can get the entire object (with _id) that I just inserted into the database.
Thanks!

After the BasicDBObject instance is inserted, the MongoDB driver modifies the instance in the terms of setting a value to the _id field (if you haven't specified such).
Therefore, you can still use the fact object and get the _id from there:
System.out.println(fact.get("_id"));

Related

Mongo Db Query to sort by the field and also aggregate the results which do not have that field

query should be sorted by 'lastUsedTimestamp' in ASC. If these entities lastUsedTimestamp is null or expired or do not have the field, we just remove them from the collection with defined limit.
I have them written like below but it is giving null
Criteria fieldsCriteria1 = Criteria.where("lastAccessTimestamp").lte(date);
Criteria fieldsCriteria2 = Criteria.where("lastAccessTimestamp").exists(false);
Query query2 = new Query();
query2.limit(3);
query2.with(Sort.by(Sort.Direction.ASC,"lastAccessTimestamp")); // to set in ASC order
query2.addCriteria(fieldsCriteria1); // to set the expired time
If i have only these above criteria added it works fine, the problem occurs when i add the below criteria
query2.addCriteria(fieldsCriteria2); // to get if the lastAccessTimestamp field is empty
I am new to Mongo Db, also I am not sure which is the best way to fulfill the above query.
I had figured out the solution, the below query worked for me.
var fieldsCriteria = new Criteria()
.orOperator(Criteria.where(LAST_ACCESS_TIMESTAMP).lt(date)
,Criteria.where(LAST_ACCESS_TIMESTAMP).exists(false)
);
var query = new Query();
query.limit(limit);
query.with(Sort.by(Sort.Direction.ASC, LAST_ACCESS_TIMESTAMP));
query.addCriteria(fieldsCriteria);
List<Document> list=mongoTemplate.find(query,Document.class,collectionName);

Why can't I query by String value when I can query by equivalent int value in Hibernate JPA with java

I was given a project at work including JPA / Hibernate
I have an object for example that is let s say described as
class SampleObject {
string value;
string othervalue;
}
and lets say that the value in the database is populated with 2 rows
table - SampleObject
row 1 - value = "21", othervalue = "some other value"
row 2 - value = "31", othervalue = "some other other value"
I can write a query that returns rows that follows
Query q = entityManager.createQuery("select s from SampleObject s where value = 21")
and I can write a query that returns rows that follows
Query q = entityManager.createNativeQuery("select * from dbo.SampleObject s where value = 21", SampleObject.class)
but what i cannot do is write those same queries as a string value and return data
ex 1:
entityManager.createQuery("select s from SampleObject s where value = '21'")
ex 2:
entityManager.createQuery("select s from SampleObject s where value = :val").setParameter("val", "21")
ex 3:
entityManager.createNativeQuery("select * from dbo.SampleObject s where value = '21'", SampleObject.class)
but as you can see this is stored as a varchar and IS REQUIRED to remain a string so i need to be able to query by a string
Disclaimer:
I am new to hibernate - very new .... very very new!
I should add in SQL SSMS I can directly query by string
I also tried using one of the suggestions below and for context it didn't resolve
You could use:
entityManager.unwrap(Session.class)
.createQuery("<your query>")
.setParameter("identifier", "3", StringType.INSTANCE);
That implementation works with the exact type that you want to pass.
I have to apologize I had an old connection string
and I was directly querying the current data in ssms and the connection string was grabbing old data in the java
my fault it was working the whole time
walking through the debugger showed old data
thank you for your help

Java mongoTemplate findOne query not returning results when id is String

I have the below query to find MongoDB document using mongoTemplate.
This is not returning any results when I search my Target using Id.
Query query = new Query(Criteria.where("id").is(String.valueOf(targetId)));
mongoTemplate.findOne(query, Target.class));
But the query works when I use any fields other than Id. Could someone help me to work this using Id.
Target class
#Data
#Document
public class Target {
#Id
private String id;
/**
* Name of the target
*/
private String name;
}
DB document.
{
"_id" : "5290d748e4",
"name" : "Test Target"
}
Query By name is working fine.
Query query = new Query(Criteria.where("name").is("Test Target"));
mongoTemplate.findOne(query, Target.class));
Based on the discussions here, it looks like this is not possible to achieve. You need to change the type in database as ObjectId.
If you cannot do that, you can do
mongoTemplate.getCollection("target").findOne(<targetId>)
But this will return a DBObject, You need to create Target instance from this
I was able to get the required functionality by using MongoCollection.
MongoDatabase mongoDatabase = mongoTemplate.getDb();
MongoCollection<Document> targetCollection
= mongoDatabase.getCollection(mongoTemplate.getCollectionName(Target.class));
Document query = new Document();
query.put("_id", parkTargetId);
query.put("spots._id", parkingSpotId);
targetCollection.find(query);

How to get the ID after inserting data into an Oracle database with Spring JdbcTemplates

I am using Spring JdbcTemplates in my project and I want to insert data into an Oracle database. Just after inserting the data I need the ID (sr_no) of this inserted value, so that I can use it.
public int addData(News newsAdd) {
int flag = 0;
String url="";
String cat = newsAdd.getNewsCat();
String language = newsAdd.getNewsLang();
// QueryConstant.newsArbian ="INSERT INTO INTERNET_NEWS(SR_NO,TITLE,NEWS_STATUS,HOME_DISPLAY,HOME_DESC,MAIN_DESC,NEWS_DATE,NEWS_CAT,IMGNEWS_URL) VALUES(seq_news.nextval,?,?,?,?,?,?,?,?)";
flag = getJdbcTemplate().update(
QueryConstant.newsArbian,
new Object[] {
newsAdd.getTitle(),
newsAdd.getStatus(),
newsAdd.getNewsHomePage(),
newsAdd.getNewsDesHom(),
newsAdd.getNewsDesMan(),
newsAdd.getDate(),
newsAdd.getNewsCat(),
url
}
);
return flag;
}
Now, there is the field sr_no in the table which is auto increment. I want to fetch the value of sr_no of the data that I inserted and pass this value to the flag variable.
How can I achieve this task?
You can use KeyHolder class for this.
Check out the section 13.5.2 Retrieving auto-generated keys using SimpleJdbcInsert on this link http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/jdbc.html#jdbc-simple-jdbc-insert-2
try GeneratedKeyHolder [docs]:(https://docs.spring.io/spring/docs/2.5.6/javadoc-api/org/springframework/jdbc/support/GeneratedKeyHolder.html)
It will return the auto-generated ID of last inserted record.

Converting DBObject to a POJO using MongoDB Java

I'm a starting to use MongoDb and developping a small web application that connect to this Mongo Database.
I have a DAO with a method to find a user from the db according to the email address assigned to the user. Each user should have a unique email address so I can assume I'll get only one document. How can then convert the DBObject to a User entity?
Here my code:
#Override
public User findUserByEmailAddress(String email) {
DB db=MongoHelper.getDb();
BasicDBObject query = new BasicDBObject();
query.put("email", email);
DBCollection users=db.getCollection("users");
DBCursor cursor = users.find(query);
DBObject user=cursor.next();
//Code to convert the DBObject to a User and return the User
}
Thank you very much in advance!
DBObject is a map, so you can get required values by simply accessing it by corresponding key.
For example:
DBObject query = QueryBuilder.start("email").is(email).get();
DBCursor cursor = users.find(query);
while (cursor.hasNext()) {
DBObject user = cursor.next();
String firstName = (String)user.get("first_name");
String lastName = (String)user.get("last_name");
//TODO: use extracted properties to build User object
}
Note that depending on document structure, the returned property can be itself a map. So appropriate casting is required. In addition, I would not assume there can be only one email per user in the document database (due to errors, wrong input etc). It should be enforced on the application level.

Categories

Resources