How to construct basicdbobject query to delete deep array documnet? - java

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);

Related

Java MongoClient to add a new embedded document

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/

Java MongoClient - Type exceptions when using Aggregate

I am getting the following exception:
com.mongodb.CommandFailureException: { "serverUsed" : "192.168.3.25:27017" ,
"errmsg" : "exception: The argument to $size must be an Array,
but was of type: EOO" , "code" : 17124 , "ok" : 0.0}
Whenever I run this pipeline using the MongoClient driver for Java:
[{ "$match" : { "_id" : "1"}}, { "$project" : { "count" : { "$size" : "$tags"}}}]
What is causing this? The pipeline works fine in the Mongo shell?
Here is my Java code:
private void countArrayLength(String id, String arrayName) {
AggregationOptions options = AggregationOptions.builder().build();
DBObject matchFields = new BasicDBObject("_id", id);
DBObject match = new BasicDBObject("$match", matchFields);
DBObject projectCount = new BasicDBObject("$size", "$" + arrayName);
DBObject projectFields = new BasicDBObject("count", projectCount);
DBObject project = new BasicDBObject("$project", projectFields);
Cursor cursor = db.getCollection(collectionName)
.aggregate(asList(match, project), options);
}
DB Structure:
{
"_id" : "1",
"_class" : "com.mongodb.BasicDBObject",
"tags" : [
{
"tag" : "tagName"
},
{
"tag" : "tagName"
},
{
"tag" : "tagName"
},
{
"tag" : "tagName"
},
{
"tag" : "tagName"
}
]
}

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 update embedded document in mongo?

I am having the following document in the mongo db.
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" : [
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
{
"name" : "rtytry",
"description" : "gffhf",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98281f00")
}],
"select":"ffdfgd"
}
I want to do automatic update of menus
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
}
I have tried using the following code:
BasicDBObject query = new BasicDBObject("_id", new ObjectId("50656f33a4e82d3f98291eff"));
BasicDBObject update = new BasicDBObject("_id", ObjectId("50656f3ca4e82d3f98291f00"));
BasicDBObject updateCommand = new BasicDBObject("$set", new BasicDBObject("menus", update));
collection.update(query, updateCommand);
The result i got is
{ "_id" : ObjectId("50656f33a4e82d3f98291eff"),
"description" : "gdfgdfgdfg",
"menus" :
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
},
"select":"ffdfgd"
}
but i want to update in the same embedded document.
Any one guide me ....Thanks in advance
Ok After having to read this a couple of times (English...) I think I understand now.
You want to upto the subdocument with the _id 50656f3ca4e82d3f98291f00 with:
{
"name" : "gdfgdfgdfg",
"description" : "dfgdgd",
"text" : "dfgdfg",
"key" : "2",
"onSelect" : "yyy",
"_id" : ObjectId("50656f3ca4e82d3f98291f00")
}
First problem you have is that your code merely sets menus field to this object. What you need is the postional operator. So you need to do a dot notation find (warning my Java is a little rusty):
query.append("menus._id", new ObjectId("50656f3ca4e82d3f98291f00"));
And then use that positional operator to update in position:
BasicDBObject update_document = new BasicDBObject("menus.$.name", my_new_subdocument.name);
update_document.append("menus.$.description", my_new_subdocument.description);
// All the other fields
BasicDBObject updateCommand = new BasicDBObject("$set", update_document);
Hopefully that should do the trick.

Java equivalent of scala query in mongodb

What is the equivalent cde in Java:
var result = collectionName.findOne()
println(result.get("name").toString)
To elaborate, This is my sample db:
{ "_id" : ObjectId("4ca039f7a5b75ab98a44b149"), "name" : "kaustubh", "country" : "india" }
{ "_id" : ObjectId("4ca03a85a12344a5e47bcc5c"), "name" : "rahul", "country" : "pakistan" }
{ "_id" : ObjectId("4ca03a9ea12344a5e47bcc5d"), "name" : "swapnil", "country" : "lanka" }
{ "_id" : ObjectId("4ca03b19a12344a5e47bcc5e"), "name" : "sagar", "country" : "nepal" }
i am running the following query on it:
query.put("country", "india");
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
that prints:
{ "_id" : { "$oid" : "4ca04b6b37a85ab92557218a"} , "name" : "kaustubh" , "country" : "india"}
as many times as the pair exists in the collection.
how do I formulate a query to get all the names, once and get the count for them.I read the docs, and didnt stumble upon any way to do it.
Try this
query.put("name", "kaustubh");
DBObject myDoc = collection.findOne(query);
System.out.println(myDoc);

Categories