1

I am new to AWS lambda, I have created sample lambda function and deploy it successfully. Now I want to connect my lambda with Mongodb and need to update collection using query but didn't get any information for the same.

I have tried integrating spring in lambda but after researching I found out that spring is not recommended and not good practice to use in lambda. I want to connect to the MongoDB database.

Below is the sample java code.

public class App implements RequestHandler<Object, Object> {


    @Override
    public Object handleRequest(Object o, Context context) {

        System.out.println("welcome to lambda function yeh.!!!");

        return null;
    }

}
0

2 Answers 2

2

You can easily connect to MongoDB without Spring.

There are a lot of tutorials out there which will help you.

For using it inside lambda, make sure to

  • package all your dependencies correctly (e.g. use the maven shade plugin)
  • handle your connections manually, as your application is not running continuously. That's not a trivial task, but there are also a lot of sources online how to do this.

As this is SO, you should try to do your first implementation yourself & if you're facing issues, please post your code and you'll get further support!

Sign up to request clarification or add additional context in comments.

Comments

1

added below maven dependency in pom.xml

  <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.3</version>
  </dependency>

written below code in handler to update query in mongoDB .

@Override
    public Object handleRequest(Object o, Context context) {

        System.out.println("welcome to lambda function yeh.!!!");
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("test");
            DBCollection col = db.getCollection("contact");
            System.out.println("data count" + col.count());

            BasicDBObject setValue = new BasicDBObject();
            BasicDBObject query = new BasicDBObject();
            query.put("contacts.mobileNo", "7090909090");
            setValue.put("contacts.$.userId", "userId12121212");
            BasicDBObject set = new BasicDBObject("$set", setValue);
            col.updateMulti(query, set);
            //close resources
            mongo.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.