Using GET to return data in MongoDB - 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.

Related

how to get data from existing mongo collection using parse server?

I am new to Parse Server.
I am having an existing collection "users" in "employee" db in Mongodb.
I need to get the users data using Parse Server.
Below is the code:
var query = new Parse.Query(users);
query.find().then((data) => {
return data;
}).catch((error) => {
return error;
});
But I am getting the error "users" is not defined.
Need some valuable help.
if your Class really is called users (which is different to the built-in Parse Server Class called User), then use :
var query = new Parse.Query('users'); //note the quotation around 'users'
If you are in fact trying to query the built-in User class, use :
var query = new Parse.Query(Parse.User);
or
var query = new Parse.Query('_User');

How to query List<BsonDocument>batch Mongo database using Field values/contents

The codes below can be used to query mongo data imported from a DataTable and output viewed via a MessageBox.I have verified that it works after some difficulties of matching uppercase and lowercase of terms to be queried
MongoClient mongo = new MongoClient("mongodb://localhost");
MongoServer server;
MongoDatabase database;
private void Form1_Load(object sender, EventArgs e)
{
server = mongo.GetServer();
server.Connect();
database = server.GetDatabase("test");
List<BsonDocument> batch = new List<BsonDocument>();
foreach (DataRow dr in dt.Rows)
{
var dictionary = dr.Table.Columns.Cast<DataColumn> ().ToDictionary(col => col.ColumnName, col => dr[col.ColumnName]);
batch.Add(new BsonDocument(dictionary));
}
MongoCollection<MongoDB.Bson.BsonDocument> collec = database.GetCollection<BsonDocument>("test");
collec.InsertBatch(batch); //// produces BsonIds for enteries
var results = batch.ToList();
string json = results.ToJson();
MessageBox.Show(json);
////Part I am struggling with
var query = new QueryDocument("Column1", "Henry");// PAY ATTENTION TO UPPER/LOWERCASE OF WORDS TO BE QUERIED
collec.Find(query).ToList(); // THIS PICKS CORRESPONDING RECORDS FROM THE MONGODB
}
The above codes worked after reconciling uppercase/lowercase of letters in the query items

MongoDB : How to find multiple documents and update at the same time?

I have mongo DB and I am using C#.Net to interact with mongo db. C# API has methods for finding a single document and updating it at the same time. For example FindOneAndUpdateAsync.
However I couldn't find any method to find multiple documents and update them at the same time asynchronously.
The code below finding and processing each document asynchronously. How do I also update that document at the same time?
public async Task<IList<IDictionary<string, string>>> DoWork()
{
var collection = _mongoDatabase.GetCollection<BsonDocument>("units");
var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Ne<string>("status", "INIT") &
(filterBuilder.Exists("isDone", false) |
filterBuilder.Eq<bool>("isDone", false));
// I want to pass this update filter to update the document. But not sure how
var update = Builders<BsonDocument>.Update
.CurrentDate("startTime");
var sort = Builders<BsonDocument>.Sort.Ascending("startTime");
var projection = Builders<BsonDocument>.Projection
.Include("_id")
.Include("fileName"); // for bravity i have removed other projection elements
var output = new List<IDictionary<string, string>>();
// How do i pass update filter and update the document at the same time??
await collection
.Find(filter)
.Sort(sort)
.Project(projection)
.ForEachAsync((unit) =>
{
var dictionary = new Dictionary<string, string>();
Recurse(unit, dictionary);
output.Add(dictionary);
});
return output.Count > 0 ? output : null;
}
That doesn't exist in the mongo .Net api see here.
Just use a combination of Find and UpdateManyAsync.

MongoDB Taking Too Long time in C#.net

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.

Copying a mongo collection using Java Driver

I want to copy the contents from one collection to another.
in mongod this can be done:
db.tempMongoItem.find().forEach( function(x){db.mongoItem.insert(x)} )
Using Java Mongo Driver, I try:
DB db = mongoClient.getDB("mydb")
CommandResult result = db.command("db.tempMongoItem.find().forEach( function(x){db.mongoItem.insert(x)} )")
But I get:
result = [serverUsed:localhost:27017, ok:0.0, errmsg:no such cmd: db.tempMongoItem.find().forEach( function(x){db.mongoItem.insert(x)} ), code:59, bad cmd:[db.tempMongoItem.find().forEach( function(x){db.mongoItem.insert(x)} ):true]]
Any ideas?
You need to emulate the same thing JS is doing in Java, which means getting a cursor and iterating over it, inserting each document into new collection.
Something like this (coll is current, coll2 is new collection):
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
coll2.insert(cursor.next());
}
} finally {
cursor.close();
}
Both coll and coll2 are assumed to be DBCollection type.
Since it appears you are copying within the same DB, there is another way to do this if you are using 2.6 MongoDB using aggregation framework $out stage:
db.collection.aggregate({"$out":"newCollection"});
Note that this is limited to outputting into the same DB that original collection is in.
The following JAVA code will copy the collection from source to destination for a given database name (using mongodb-driver 3.0.4)
/** Clone a collection.
*
* #param fromCollectionName - The name of collection to be cloned
* #param toCollectionName - The name of the cloned collection
* #param dbName - The name of the database
*/
public void cloneCollection(String fromCollectionName, String toCollectionName, String dbName) throws MongoException {
MongoCollection toCol = this.getCollection(toCollectionName, dbName);
if (toCol != null) {
throw new MongoException("The destination collection already exists.");
}
List<Document> ops = new ArrayList<>();
ops.add(new Document("$out",toCollectionName));
MongoCollection sourceCollection = this.getCollection(fromCollectionName, dbName);
sourceCollection.aggregate(ops);
}
public MongoCollection getCollection(String collection, String dbName) {
MongoClient mongo = new MongoClient(new ServerAddress("localhost", Integer.parseInt(port)));
MongoDatabase database = mongo.getDatabase(dbName);
return curdb.getCollection(collection);
}
Please note that this will not copy over the indices that you have created in source collection. You will have to copy the indices seperately
Following up on Asya's response, you can use Java 8 Lambda functions to do:
collSource.find().forEach((Block<Document>) collTarget::insertOne);