To use IN clause in MongoDB, we need to create the list and set the list as value with key as "$in"
In our last post, we learned how to find the document with where clause within a collection. This post will illustrate on how to find documents from a collection using IN clause.
First Insert Records in a Collection.
In the above example, collection Loan is created with 2 parameters :
1) name/type of loan
2) Interest rate
To find a document where name = "Personal Loan" or "Home Loan", we need to use "$in" as a key.
Refer to example :
import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; public class MongoDBFindJava { public static void main(String args[]) throws UnknownHostException { DB database = getDatabase(); DBCollection collection = database.getCollection("loans"); // To find a record where Name IN BasicDBObject inQuery = new BasicDBObject(); List<String> list = new ArrayList<String>(); list.add("Personal Loan"); list.add("Home Loan"); inQuery.put("name", new BasicDBObject("$in", list)); DBCursor cursor = collection.find(inQuery); while(cursor.hasNext()) { System.out.println(cursor.next()); } } public static DB getDatabase() throws UnknownHostException { Mongo mongo = new Mongo("localhost", 27017); DB database = mongo.getDB("yourdb"); return database; } }
No comments:
Post a Comment