Java MongoClient to add a new embedded document - java

I have a below data type in mongodb
{
"_id" : ObjectId("60007b3abc54b5305e9f5601"),
"description" : "Mens",
"name" : "Men"
}
Since the above data is already an existing data, Now using the MongoClient I want to insert the new embedded document based on the _id as below
{
"_id" : ObjectId("60007b3abc54b5305e9f5601"),
"description" : "Mens",
"name" : "Men",
"subCategory" : [{
"name" : "This is name update",
"description" : "This is update"
}]
}
Once, the array has been inserted, Again I have the requirement to add another item to the array, something like below
{
"_id" : ObjectId("60007b3abc54b5305e9f5601"),
"description" : "Mens",
"name" : "Men",
"subCategory" : [{
"name" : "This is name update",
"description" : "This is update"
},
{
"name" : "This is name update",
"description" : "This is update"
}]
}

Code to update :
import static com.mongodb.client.model.Filters.eq;
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("some_db_name");
MongoCollection<Document> collection = database.getCollection("some_database");
Document document = collection.find(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")))
.first();
Object object = document.get("subCategory");
List<Document> documents = new ArrayList<>();
if(object != null) {
documents = (List<Document>) object;
}
documents.add(new Document("name", "This is name update")
.append("description", "This is update"));
document.append("subCategory", documents);
collection.updateOne(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")),
new Document("$set", new Document("subCategory", documents)));
Read docs : https://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

Related

how to insert an embedded document in a collection in MongoDB using java

I have a collection in which I want to add an embedded document using java.I am able to add a normal document. But how to add an embedded document. The structure of the collections is supposed to be like this:
{
"_id" : ObjectId("591a93f7f0bf98b7253bf187"),
"INTEGRATION_ID" : null,
"STATUS_CD" : "Open",
"X_CUST_REF" : "AUTO ECOSSE",
"REQ_SHIP_DT" : "2014-03-21:00:00:00",
"QUOTE_ID" : null,
"ACCNT_ID" : "1-TGCG-1",
"ACTIVE_FLG" : "WQ==",
"PROCESS_TIMESTAMP" : "2017-04-19:15:27:34.786214000",
"CONTACT_ID" : "2-16D8S576",
"BU_ID" : "1-ENQCIQ",
"SHIP_CON_ID" : "No Match Row Id",
"LAST_UPD" : "2014-03-20:00:00:00",
"X_CLOSE_DT" : null,
"X_SUB_STAT" : "In Progress",
"ORDER_NUM" : "BTAQZ635",
"SOFT_DELETE" : "N",
"ROW_ID" : "2-16R75TLQ",
"LAST_UPD_BY" : "1-2SEO0FD",
"REV_NUM" : "1",
"ORDER_DT" : "2014-03-20:00:00:00",
"ORDERLINE" : [
{
"ASSET_ID" : null,
"SERV_ACCNT_ID" : null,
"REQ_SHIP_DT" : "2014-03-21:00:00:00",
"X_PROD_DESC" : "Mongo Kafka",
"SHIP_CON_ID" : null,
"X_BES_STATUS" : "Not Possible To Be Fulfiled",
"ROW_ID" : "2-16R75TM0",
"STATUS_CD" : "FAILED",
"ORDER_ID" : "2-16R75TLQ",
"COMPLETED_DT" : null,
"LAST_UPD" : "2014-03-20:00:00:00",
"SOFT_DELETE" : "N",
"INTEGRATION_ID" : "BTAQZ6351-1",
"X_CDD" : "2014-03-21:00:00:00",
"ACTION_CD" : "Add",
"X_ORDER_ITEM_SUBSTATUS" : "Failed",
"X_APPT_REF" : null,
"X_CANCELLED_DT" : null,
"PROD_ID" : "1-7OSVB0F",
"SERVICE_NUM" : "01382459732",
"MUST_DLVR_BY_DT" : null,
"ROLLUP_FLG" : "N",
"ROOT_ORDER_ITEM_ID" : "2-16R75TM0",
"BILL_ACCNT_ID" : "2-1Y2ZD-101",
"PROCESS_TIMESTAMP" : "2016-03-28:15:09:06.274774000",
"QTY_REQ" : "1"
}
]
}
How do get the ORDERLINE embedded array in my collection?
Connect the DB
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
Get/create the Collection and add parent data
DBCollection collection = db.getCollection("dummyColl");
BasicDBObject document = new BasicDBObject();
document.put("INTEGRATION_ID", "mkyongDB");
document.put("STATUS_CD" : "Open",);
........
........
Push child collection into the Object
BasicDBObject OrderLineDetail = new BasicDBObject();
OrderLineDetail .put("ASSET_ID", null);
OrderLineDetail .put("SERV_ACCNT_ID", null);
OrderLineDetail .put("REQ_SHIP_DT", "Mongo Kafka");
document.put("ORDERLINE", OrderLineDetail );
Save the data
collection.insert(document);

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 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 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 match a document with existing array elements in mongodb using java driver

Hello all i am trying to match a document using mongodb java driver for eg :
{
"fName" : "abc",
"lName" : "456",
"dob" : "00",
"address" : "xyz"
}
with
"nameIdentity" : [
{
"fName" : "abc",
"lName" : "def",
"dob" : "00",
"address" : "xyz"
},
{
"fName" : "123",
"lName" : "456",
"dob" : "00",
"address" : "789"
}
If i found the document then i don't do anything else add the document. My problem here is if my source document contains fname : abc and lname: 456 this is matching fname in the first set of nameIdentity and lname in the second set of identity. I want this to be a one complete match. I have tried something like this
List<Document> nameIdentities = (List<Document>) matchedDocument.get("nameIdentity");
for (int i=0;i<nameIdentities.size();i++)
{
temp.add(nameIdentities.get(0));
quBasicDBObject=new BasicDBObject("$and",temp);
}
iterable = mongoDatabase.getCollection("entity").find(updatedDocumentTypeOne);
if (iterable.first() == null)
{
updateResult = mongoDatabase.getCollection("entity")
.updateOne(
new Document("_id", new ObjectId(objectId)),
new Document("$push", new Document("nameIdentity", nameList.get(0))));
}
any suggestions where am i going wrong?
UPDATE
You may have to use the aggregation framework.
Maybe something like:
List<Bson> filterList = new ArrayList<>();
filterList.add(new BsonDocument().append("nameIdentity.fName", new BsonString("abc") ));
filterList.add(new BsonDocument().append("nameIdentity.lName", new BsonString("456") ));
FindIterable<org.bson.Document> it = collection.find(Filters.and(filterList));

Categories