MongoDB Taking Too Long time in C#.net - mongodb

I am retrieving data from mongoDB using C# driver, It is taking a lot of time when i do to list Please help me
My Mongoquery is
var documentReportIds = new BsonValue[] { LatestReportIds };
var documentChennelIds = new BsonValue[] { Cid };
var documentPropertyIds = new BsonValue[] { Pid };
IMongoQuery query = new QueryDocument();
query = Query.And(Query.GTE("CheckInDate", startdate.Date.AddMinutes(330)),
Query.LTE("CheckInDate", endDate.Date.AddMinutes(330)));
query = Query.And(query, Query.EQ("SubscriberPropertyId", reportFilter.SubscriberPropertyId));
query = Query.And(query, Query.EQ("LengthOfStay", reportFilter.LOS));
query = Query.And(query, Query.In("ReportId", documentReportIds));
query = Query.And(query, Query.In("ChannelId", documentChennelIds));
query = Query.And(query, Query.In("PropertyId", documentPropertyIds));
MongoDBEntities<ScheduleOptimizationReportDetails> _obj = new MongoDBEntities<ScheduleOptimizationReportDetails>();
var list= _obj.GetSchedularOptimizationJoin(query);
Class from where it perform data retrieving
public class MongoDBEntities<T>
{
MongoDatabase db = MongoDBInstance.GetMongoDatabase;
public List GetSchedularOptimizationJoin(IMongoQuery query)
{
MongoCollection MCollection = db.GetCollection(“Subscription_OptimisedReports”);
MongoCursor cursor = MCollection.FindAs(query).SetFields(Fields.Include(“ScheduleLogId”, “SubscriberPropertyId”, “CheckInDate”, “ReportId”, “CreatedDate”));
List entities = cursor.ToList();
return entities ;
}
}
what is another option to select data in C#, I have also applied indexing on column.
Please help me how to solve it.

You can use the MongoDB.Driver.Linq package to help you create your querys with Linq expressions.

Related

How do I iterate through entries in MongoDB 3.0?

We are trying to retrieve entries from the database (MongoDB) and place them in a db. When using DBCursor, we use cursor.hasNext() to get the next reading.
DBCursor is depreciated in MongoDB 2.0 and it is recommended to use FindIterable for MongoDB 3.0.
However when we use FindIterable, there isn't a similar hasNext() method.
How do I change my code below for 3.0?
BasicDBObject query = new BasicDBObject("timeStamp",
new BasicDBObject("$gte",from).append("$lt",to ));
DBCursor cursor = (DBCursor) newColl.find(query);
//FindIterable cursor = newColl.find(query);
while (cursor.hasNext()) {
DBObject latestEntry = cursor.next();
String json = latestEntry.toString();
Reading reading = gson.fromJson(json, Reading.class);
readingList.add(reading);
}
return readingList;
You can try something like below.
Document query = new Document("timeStamp",
new Document("$gte",from).append("$lt",to));
FindIterable<Document> find = newColl.find(query);
for (Document latestEntry : find) {
String json = latestEntry.toJson();
Reading reading = gson.fromJson(json, Reading.class);
readingList.add(reading);
}
return readingList;
Using Cursor
MongoCursor<Document> cursor = newColl.find(query).iterator();
while (cursor.hasNext()) {
Document latestEntry = cursor.next();
String json = latestEntry.toJson();
Reading reading = gson.fromJson(json, Reading.class);
readingList.add(reading);
}
return readingList;
Using Lambda
List<Reading> readingList= newColl.find().map(item -> gson.fromJson(item.toJson(), Reading.class)).into(new ArrayList<>());

Using GET to return data in MongoDB

I am trying to connect to MongoDB with Web Api, trying to return the connected data in MongoDB using Get. The name of the database is "test" and the collection name is "restaurant".
Here is the code I have
public IEnumerable<restaurants> Get()
{
var client = new MongoClient();
var dbs = client.GetDatabase("test");
var collection = dbs.GetCollection<restaurants>("restaurants");
return collection;
}
The last collection word is underlined, and I have not found what needs to be returned (in place of collection) in order to show the database in MongoDB (using postman).
I think you are trying to return IMongoCollection, not IEnumerable so last line is underlined :)
Try to transform collection to List (asynchronously), then return. For example:
public Task<List<restaurants>> GetRestaurantsAsync()
{
var client = new MongoClient();
var dbs = client.GetDatabase("test");
var collection = dbs.GetCollection<restaurants>("restaurants");
return await collection.Find(_ => true).ToListAsync();
}
public async Task MainAsync()
{
List<restaurants> restaurantsList = await GetRestaurantsAsync();
}
Note: it depends on which version of mongo c# driver you're using.

how rebuild lucene indexes over hibernate search jpa with mongodb

I have accidentally deleted my index directory, now i am trying to rebuild all indexes.
I am using the hibernate search with JPA, lucene and MONGODB.
the following method is returning no results
public void rebuildIndex()throws Exception{
org.hibernate.search.jpa.FullTextEntityManager fem = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
org.hibernate.search.query.dsl.QueryBuilder queryBuilder = fem.getSearchFactory().buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = queryBuilder.all().createQuery();
FullTextQuery fullTextQuery = fem.createFullTextQuery(query, Person.class);
//fullTextQuery.initializeObjectsWith(ObjectLookupMethod.SKIP, DatabaseRetrievalMethod.FIND_BY_ID);
System.out.println(fullTextQuery.toString());
List<Person> results = fullTextQuery.getResultList();
fem.clear();
System.out.println(results.size());
for(Person p : results){
fem.index( p );
fem.flushToIndexes();
fem.clear();
}
//fem.createIndexer().startAndWait();
}
the method is returning no result. how should I get all data from mongoDb to rebuild index?
as hibernate search didn't work with criteria neither with JPQL and has his own JP-QL parser.
I couldn't create a findAll method to retrieve all objetcs
the only way was use a native mongoDb query:
org.hibernate.search.jpa.FullTextEntityManager fem = org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
Mongo mongo = new Mongo("127.0.0.1", 27017);
DB db = mongo.getDB("mainBase");
DBCollection dbCollection = db.getCollection("Persons");
DBCursor cursor = dbCollection.find();
Collection<String> ids = new ArrayList<String>();
String id = "";
while (cursor.hasNext()) {
id = cursor.next().get("_id").toString();
System.out.println(id);
ids.add(id);
}
System.out.println(">"+ids.size());
Person pes;
for(String p : ids){
pes = new Person();
pes.setId(p);
pes = find(pes);
System.out.println("indexing: "+pes.getId());
fem.index( pes );//index each element
fem.flushToIndexes();//apply changes to indexes
fem.clear();//free memory since the queue is processed
}

Query without condition in MongoDB + C#

I'm trying to use the collection.FindAndModify and give it a IMongoQuery which selects all the documents. But I can not find how to create a query without any conditions!
Can anyone tell me how to do this? I'm using MongoDB C# Driver v1.8.3.
Here's my code:
var query = ???;
var sortBy = SortBy.Ascending(new string[] { "last_update" });
var update = Update<Entity>.Set(e => e.last_update, DateTime.Now);
var fields = Fields.Include(new string[] { "counter", "_id" });
var m = collection.FindAndModify(query, sortBy, update, fields, false, false);
I wonder what should I write in place of ??? to select all the documents!?
Use an empty QueryDocument:
var query = new QueryDocument();
But keep in mind that FindAndModify will only modify the first matching document.

MongoDb: how to return distinct field in select (find) with C# official driver

I need to select User Name from the collection of Users. I do it in a such way:
MongoCollection<Enums> coll = Db.GetCollection<Enums>("Users");
var query = Query.EQ("_id", id);
var res = coll.FindOne(query);
var name = res.Name;
var url = res.UserUrl; //or some more fields, not just Name
Assuming that User document can contain a lot of data, and there is no need to transfer the whole user document, how to select only a few distinct fields, using official C# driver?
You'll have to use a function that returns a MongoCursor.
In the MongoCursor you can specify the fields you want to return.
var result = Db.GetCollection<Enums>("Users").FindAll();
result.Fields = Fields.Include(new [] {"Name"});;
foreach (var user in result)
{
Console.WriteLine(user.Name);
}