working with Mongo db + Java (subcollections)

subcollectionsCRUD.png

In the previous post we have seen different ways to use find() method. Today lets check out different operations we can perform on Sub Collections.

Index:

  • Creating a sub Collection in Collection
  • Adding Objects to sub collections
  • Updating sub collection data
  • Removing Objects from Sub Collection
  • Removing Sub Collection

Creating a sub Collection in Collection:

In mongo DB:

db.users.update({},{"Address":[]})

In Java :

Document subCollection = new Document("$set", new Document("Address",new ArrayList<Object>()));
         Document query = new Document();
         UpdateResult result =collection.updateMany(query, subCollection);
         if(result.isModifiedCountAvailable()){
         System.out.println("sub collections added");
         }else{
         System.err.println("not added");
         }

Adding Objects to sub collections:

In mongo DB:

db.users.update({"_id" : ObjectId("583febc7ac9dd6aa88de4fc6")},{$push:{"Address":{"city":"Banglore","country":"india","zipcode":"someZipCode"}}})

In Java :


Document subCollectionObject1 = new Document("city", "Banglore").append("country", "india").append("zipcode", "someZipCode");
        Document subCollectionObject2 = new Document("city", "Chennai").append("country", "india").append("zipcode", "5211251");
        Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject1))));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject2))));

Updating sub collection data:

Since we don’t know the position of the Object in the array we use position parameter ‘$’

In mongo DB:

db.users.update({"Address.zipcode":"someZipCode"},{$set:{"Address.$.zipcode":"524896"}})

In Java :


 Document query2 = new Document("Address.zipcode", "someZipCode");
 collection.updateOne(query2, new Document("$set", new  Document("Address.$.zipcode","524896")));

Removing Objects from Sub Collection:

$pull works on Array, so we have to give array and the conditions, from which we have to remove array

In mongo Db:

db.users.update({"Address.zipcode":"524896"},{$pull:{"Address":{"zipcode":"524896"}}})

In Java :


 Document query2 = new Document("Address.zipcode", "someZipCode");
 collection.updateOne(query2, new Document("$set", new  Document("Address.$.zipcode","524896")));

Removing Sub Collection:

In mongo DB:

db.users.update({"_id" : ObjectId("583febc7ac9dd6aa88de4fc6")},{$unset:{"Address":1}})

In Java :


  Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
         collection.updateOne(query1, new Document("$unset", new Document("Address", 1)));

Below is full java program

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import org.bson.Document;
import org.bson.types.ObjectId;

public class OperationsOnSubCollections {

    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient("localhost");
        MongoDatabase database = mongoClient.getDatabase("library");

        MongoCollection collection = database.getCollection("users");

        // create a sub collection
        Document subCollection = new Document("$set", new Document("Address", new ArrayList<Object>()));
        Document query = new Document();
        UpdateResult result = collection.updateOne(query, subCollection);
        if (result.isModifiedCountAvailable()) {
            System.out.println("sub collections added");
        } else {
            System.err.println("not added");
        }

        // Add objects to the subcollectins
        Document subCollectionObject1 = new Document("city", "Banglore").append("country", "india").append("zipcode", "someZipCode");
        Document subCollectionObject2 = new Document("city", "Chennai").append("country", "india").append("zipcode", "5211251");
        Document query1 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject1))));
        collection.updateOne(query1, new Document("$push", new Document("Address", new Document(subCollectionObject2))));

        // modify data in sub collectin objects
        //(since we dont know the exacet posing of the onject in Address Array we use '$' as a positional parameter)
        Document query2 = new Document("Address.zipcode", "someZipCode");
        collection.updateOne(query2, new Document("$set", new Document("Address.$.zipcode", "524896")));

        // delete a sepecific sub collectin Object
        // $pull workes on Array, so have to give array and the conditons, from which i have to remove array
        Document query3 = new Document("Address.zipcode", "someZipCode");
        collection.updateOne(query3, new Document("$pull", new Document("Address", new Document("zipcode", "524896"))));

        // delete a key from colleciton
        Document query4 = new Document("_id", new ObjectId("583febc7ac9dd6aa88de4fc5"));
        collection.updateOne(query4, new Document("$unset", new Document("Address", 1)));

    }

 

Advertisements

About sivateja

I am a professional graduate..I am passionate about Latest Technology.
This entry was posted in mongodb and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s