My MongoDB Data looking like Below:-
{
"_id": 1,
"categories":[
{
"categoryName": "Automobiles",
"categoryId": 1,
"catDisplayName": "language1",
"subCategories": [
{
"subCategoryName": "cars",
"subCategoryId": 1,
"subCatDisplayName": "language2"
},
{
"subCategoryName": "bykes",
"subCategoryId": 2,
"subCatDisplayName": "language3"
}
]
},
{
"categoryName": "Electronics",
"categoryId": 2,
"catDisplayName": "somelanguage1",
"subCategories": [
{
"subCategoryName": "Mobiles",
"subCategoryId": 1,
"subCatDisplayName": "somelanguage2"
},
{
"subCategoryName": "cameras",
"subCategoryId": 2,
"subCatDisplayName": "somelanguage3"
}
]
}
]
}
We are trying two cases with MongoDb Casbah the following cases are:-
if catagory exists and subCategory doesn't exist then update the subcategory in subCategories Array
if catagory doesn't exist and subCategory doesn't exist then update the category and subCategory in categories and subCategories Array Respectively
My Case 1 code looking like this it is working fine
val builderObj = MongoDBObject.newBuilder
builderObj += "subCategoryName" -> "cycles"
builderObj += "subCategoryId" -> 3
builderObj += "subCategoryName" -> "language4"
builderObj.result ()
val query = MongoDBObject("categories.categoryName" -> "Automobiles")
val updatingdata = $addToSet("categories.$.subCategories" -> builderObj.result ())
collection.update(query,updatingdata,true,true)
But How to Write For Case 2 We are trying like below
val builderObj1 = MongoDBObject.newBuilder
builderObj1 += "categoryName"-> "Entertainment"
builderObj1 += "categoryId"-> 3
builderObj1 += "catDisplayName"-> "somelanguage4"
val builderObj = MongoDBObject.newBuilder
builderObj += "subCategoryName" -> "Tickets"
builderObj += "subCatDisplayName"-> "language1"
builderObj += "subCategoryId" -> 1
builderObj.result ()
val query = MongoDBObject("categories.$.categoryName" -> "Entertainment") //Entertainment Category doesn't exist in my data
val updatingdata = ? // How To Update the Cateroy and SubCategory at a time
collection.update()
Please give me Suggestions i am struck here
Best Regards GSY
Since you are creating a new category, the
subCategories
array of the new category will be empty. So you can just add it to the new category directly.Of course this will update every element of
collection
to add the new category. If you want to be more selective, you'll need to updatequery
appropriately.