I am new to MongoDB
. By default, collections in mongodb
have index on _id
field.I need to create an index on 2 more fields using Java.
DBObject indexOptions = new BasicDBObject();
indexOptions.put(field_1, 1);
indexOptions.put(field_2, -1);
collection.createIndex(indexOptions )
When i query that in mongodb using db.collection_name.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "schema.collection_name"
},
{
"v" : 1,
"key" : {
"field_1" : 1,
"field_2" : -1
},
"name" : "field_1_1_field_2_-1",
"ns" : "schema.collection_name"
}
]
I am not sure if the above is correct. Can someone please confirm? If not correct,how can i correct it ?
Adding to the above, for retrieval i am doing something like this:
DBObject subscriberIdObj = new BasicDBObject( field3, value3 );
DBObject subscriberIdIsNullObj = new BasicDBObject( field3, null );
BasicDBList firstOrValues = new BasicDBList();
firstOrValues.add( subscriberIdObj );
firstOrValues.add( subscriberIdIsNullObj );
DBObject firstOr = new BasicDBObject( "$or", firstOrValues );
DBObject batchIdObj = new BasicDBObject( field1, value1 );
DBObject fileNameObj = new BasicDBObject( field2, value2 );
BasicDBList secondOrValues = new BasicDBList();
secondOrValues.add( batchIdObj );
secondOrValues.add( fileNameObj );
DBObject secondOr = new BasicDBObject( "$or", secondOrValues );
BasicDBList andValues = new BasicDBList();
andValues.add( firstOr );
andValues.add( secondOr );
DBObject query = new BasicDBObject( "$and", andValues );
DBCursor cursor = mongoDatastore.getDB().getCollection(collection_name).find(query);
Now, for fast retrieval like above should i create index separately on field1,field2 and field3? or compound index on all the 3 fields?