Can we query with _id object on mongodb with mongoClient - mongodb

I am trying to query on mongodb with _id field
I am doing it like this
1st way:
MongoDatabase mongoDatabase = mongoClient.getDatabase(mongoDatabaseName);
FindIterable<MyEntity> iterable =
mongoDatabase.getCollection(tablename).find(eq("_id",
agentId), MyEntity.class);
iterable.getFirst(); // Thats always null
2nd way:
Document document =
mongoDatabase.getCollection(tableName).find(eq("_id", new
ObjectId(agentId))).first();
with 2nd way , document is there ,but then i am not able to change it to my Entity , I tried with converting from json with jackson , but then it gives error because in my entity there is "id" not "_id" and thats a string , not object.
Can i get some hint please.

Related

With Spring Data in MongoDB, can I search by a missing field? [duplicate]

Situation:
I have collection with documents, each document contains such fields: "_id"(ObjectId), "userId"(String), but it also can be field "files"(Object).
When I'm doing this:
final Query query = new Query();
query.fields().include("_id");
final List<File> fileList = mongo.find(query, File.class);
As a result I'm getting fileList with all records and that is fine.
But when I'm doing like that, to get records only where "files" field exists - result is error.
final Query query = new Query();
query.fields().include("files");
final List<File> fileList = mongo.find(query, File.class);
Does error occur because I'm trying to get Object field? And how I can solve this with Query or Criteria?
You can construct this Query to get all documents that contains files filed:
Query.query(Criteria.where("files").exists(true))
Another possibility is to use org.springframework.data.mongodb.repository.Query annotation on your method (useful when using MongoRepository):
#Query(value="{ files : { $exists : true } }")

Update Value in Mongo 3.6.0 while updating value inside json object

I want to update FieldA in someFields while someFields is null in MongoDB
{
"someFileds : {
"FieldA" : "ABS"
}
}
someFields may have more fields as well but Just want to ensure that other fields won't be overridden.
Sometime SomeFields won't be having any fields so want to
I am using below code for set the the value however value for someFields is null in MongoDB.
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("SomeFields.FieldA", "TEST");
Could you please suggest how can handle the null in this scenario.
Use this Mongo update query.
db.collection.update({}, {$set:{"someFields": {"FieldA": "Test"}}});
It will create FieldA in someFields when it is null otherwise will only update FieldA.
In your case kindly pass object all time in 2nd parameter of put.
dbObject.put("SomeFields", {FieldA:"TEST"});

how to get all the documents in collection from mongoDB using spring

I was trying to get all the documents from a collection in mongoDB , I am using spring.
MongoTemplate mongoOperation = SpringMongoConfig1.mongoTemplate()
Here in monngoOperation I did not find any method which returns all the docs from a collection .
can anyone help in this ?
If you want to find all the documents of JavaDocumentName(any collection name in java)
List<JavaDocumentName> listRes = mongoOperation.findAll(JavaDocumentName.class);
You can do like this:
//If you don't need connection's configures. i.e. your mongo is in you localhost at 127.0.0.1:27017
MongoClient cliente = new MongoClient(); //to connect into a mongo DB
MongoDatabase mongoDb = client.getDatabase("DBname"); //get database, where DBname is the name of your database
MongoCollection<Document> robosCollection = mongoDb.getCollection("collectionName"); //get the name of the collection that you want
MongoCursor<Document> cursor = robosCollection.find().cursor();//Mongo Cursor interface implementing the iterator protocol
cursor.forEachRemaining(System.out::println); //print all documents in Collection using method reference

Specify datatypes while updating MongoDB document using Casbah

I have a MongoDB document that I need to update using Casbah for scala. My mongoDB document looks like
{"_id": ObjectId("58d86364fbb1bb2224cab56a"),
"record_interval":
[
{
"record_time": ISODate("2017-01-26T09:22:15.000Z"),
"insert_time": ISODate("2017-03-26T12:57:08.610Z"),
"reading1": 50.0,
"reading2": 627.0
}
],
"record_id": "1234",
"record_hour": ISODate("2017-01-26T09:00:00.000Z")
}
I inserted the above document using df.write methodology, so I was able to specify the schema with datatypes when I created the dataframe and was able to successfully insert the document with the the specified datatypes.
Now, I need to add an object inside the record interval array. I have a JSON string that I parsed as a DBObject
val DBobject: DBObject = JSON.parse(Json_String).asInstanceOf[DBObject]
The DBobject that looks like below
{
"vib_temp": "55.0",
"vib_voltage": "647.0",
"message_time": "2017-01-26 03:48:52.000000",
"etl_date_time": "2017-03-26 06:57:09.302000"
}
I added this DBObject into the record_interval array of the aforementioned document using the below code.
collection.update(MongoDBObject("_id" -> new ObjectId("58d86364fbb1bb2224cab56a"))
,$push("record_interval" -> new MongoDBObject(DBobject)))
I am able to update the desired document, but the datatypes of the elements record_time, insert_time, reading1 and reading2 are all strings. Whereas I would like to insert the object with appropriate datatypes. How do I specify the datatypes while updating the document? Thanks in advance
I found that the DBObject that I am trying to insert should have the values with the desired data type.
Following worked for me.
val Current_datetime = new DateTime()
val message_time = new DateTime()
collection.update(MongoDBObject("_id" -> new ObjectId("58d86364fbb1bb2224cab56a"))
,$push("record_interval" -> new MongoDBObject(
,("vib_temp"->55.0)
,("vib_voltage"->647.0)
,("message_time"->message_time)
,("etl_date_time"-> Current_datetime))))

Update an array using Jongo

I have a mongodb collection of the form
{
"_id":"id",
"userEmail":"userEmailFromCustomerCollection",
"customerFavs":[
"www.xyz.com",
"www.xyz.com",
"www.xyz.com"
]
}
I need to add an element to the customers favs array using Jongo , I am using the following code snippet to do so .
String query = "{userEmail:'"+emailId+"'}";
customerFavCollection.update(query).with("{$addToSet:{customerFavs:#}}", favUrl);
My problem , is that I need to upsert the document if the document does not
exist already , how can I do so using Jongo, I know an easier option would be to retrieve the document by Id and if it does not exist then insert the document using save() , but I am trying to avoid the extra retrieve.
You can add upsert() on the query.
customerFavCollection.update("userEmail:#", emailId)
.with("{$addToSet:{customerFavs:#}}", favUrl)
.upsert();