I'm trying to do a select at a Mongo database
I'm using this DLL
MongoDB.Bson,MongoDB.Driver,MongoDB.Driver.Linq
My table have more than 55k rows
After some time occurs this error
Cursor Not Found
Here is my code
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("Database");
var collection = database.GetCollection<DesktopSessions>("desktop_sessions");
var query = (from e in collection.AsQueryable<DesktopSessions>()
where e.created_at > new DateTime(2012, 7, 1)
select e);
foreach (var item in query)
{
string id = item._id.ToString();
}
How can I solve this problem?
I changed my code to this
var collection = database.GetCollection<DesktopSessions>("desktop_sessions");
var queryM = Query.GTE("created_at", new BsonDateTime(new DateTime(2012,7,1)));
var cursor = collection.Find(queryM);
cursor.SetFlags(QueryFlags.NoCursorTimeout);
It Works!!
Other option is to set the timeout for whole database which is what I am doing.
You can do it in configuration, command line, mongo shell, or even C#.
see here:
https://jira.mongodb.org/browse/SERVER-8188
This is the solution I am using currently in my init class
var db = this.MongoClient.GetDatabase("admin");
var cmd = new BsonDocumentCommand<BsonDocument>(new BsonDocument {
{ "setParameter", 1 },
{ "cursorTimeoutMillis", 3600000 }
});
db.RunCommand(cmd);
More information could be find here:
https://docs.mongodb.com/v3.0/reference/parameters/#param.cursorTimeoutMillis
Related
I think I am on the right path, but my C# code is not creating document in Azure CosmosDB.
Below is my documentdb code:
using (var client = new DocumentClient(new Uri(endpoint), authkey))
{
Database database = client.CreateDatabaseQuery("SELECT * FROM c WHERE c.id = 'db'").AsEnumerable().First();
var query = new SqlQuerySpec
{
QueryText = "SELECT * FROM c WHERE c.id = #id",
Parameters = new Microsoft.Azure.Documents.SqlParameterCollection { new Microsoft.Azure.Documents.SqlParameter { Name = "#id", Value = collectionId }
}
};
DocumentCollection collection = client.CreateDocumentCollectionQuery(database.SelfLink,query).AsEnumerable().First();
dynamic document1Definition = new
{
name = "Admin",
address = 1,
};
var result = client.CreateDocumentAsync(collection.SelfLink, document1Definition);
}
Also want to point out, currently there are no columns named as "name" and "address" in my collection. So according to my knowledge they are suppose to be created dynamically. Please let me know what wrong are you doing?
See last statement, you are using c# Async method without await.
Use await client.CreateDocumentAsync(collection.SelfLink, document1Definition); or your code will exit before document creation is finished.
Note that your method should change to public async Task methodname(), you will see related tip shown by VS.
Some references for you
Async and Await
How and when to use async and-await
I followed this tutorial but the nuget package is old and a new package is used now MongoDB.Driver https://www.codeproject.com/Articles/656093/Connecting-MongoDB-with-ASP-NET So the syntax is different and i can itterate through the elements. Here's what I've got till now.
List<Info> list = new List<Info>();
var server = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
IMongoDatabase database = server.GetDatabase("DB");
IMongoCollection<Info> valuti = database.GetCollection<Info>("Vals");
We could use Find(_=>true) method of IMongoCollection<> and iterate it
List<Info> list = new List<Info>();
var server = new MongoClient(MongoUrl.Create("mongodb://localhost:27017"));
IMongoDatabase database = server.GetDatabase("DB");
IMongoCollection<Info> valuti = database.GetCollection<Info>("Vals");
vaulti.Find(_=>true).ToList().ForEach(vault => {
//Iteration
});
So for sqlite I would just do:
var d = new ConnectionHandler();
var writeData =
$"UPDATE `Books` SET Book_Author = #Book_Author WHERE ID = 1";
d.OpenCnx();
using (var cmd = new SQLiteCommand(writeData, d.cnx))
{
cmd.Parameters.AddWithValue("#Book_Author", $"New Book owner");
cmd.ExecuteNonQuery();
}
but for Mongodb for c# what would be the equivalent, or how would I do this
You can get some inspiration for updating a document in the quick-tour documentation provided on the MongoDB site: http://mongodb.github.io/mongo-csharp-driver/2.5/getting_started/quick_tour/
Just look at the Updating Document section.
But to save a click you can use the following code as an inspiration:
// Setup the connection to the database
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("Library");
var collection = database.GetCollection<BsonDocument>("books");
// Create a filter to find the book with ID 1
var filter = Builders<BsonDocument>.Filter.Eq("ID", 1);
var update = Builders<BsonDocument>.Update.Set("Book_Author", "New Book owner");
collection.UpdateOne(filter, update);
I hope this helps.
I try to get all data from collection into MongoDB server using C# driver.
The idea is connect to the server and get all collection than insert into list of class.
List<WatchTblCls> wts;
List<UserCls> users;
List<SymboleCls> syms;
public WatchTbl()
{
InitializeComponent();
wts = new List<WatchTblCls>();
users = new List<UserCls>();
syms = new List<SymboleCls>();
}
public async void getAllData()
{
client = new MongoClient("mongodb://servername:27017");
database = client.GetDatabase("WatchTblDB");
collectionWatchtbl = database.GetCollection<WatchTbl>("Watchtbl");
collectionUser = database.GetCollection<UserCls>("Users");
collectionSymbole = database.GetCollection<SymboleCls>("Users");
var filter = new BsonDocument();
using (var cursor = await collectionWatchtbl.FindAsync(filter))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var document in batch)
{
wts.Add(new WatchTblCls(document["_id"], document["userId"], document["wid"], document["name"], document["Symboles"]));
}
}
}
}
I get this error under
wts.Add(new WatchTblCls(document["_id"], document["userId"], document["wid"], document["name"], document["Symboles"]));
Cannot apply indexing with [] to an expression of type 'WatchTbl'
I don't understand the reason behind using WatchTbl and WatchTblCls both together. Is WatchTblCls a model for the entity WatchTbl here? Im not sure.
In any case. If you go for aggregation and want to convert WatchTbl collection to WatchTblCls list, your desired solution might look like the following. I don't know the defiitions of the classes so I'm assuming:
var client = new MongoClient("mongodb://servername:27017");
var database = client.GetDatabase("WatchTblDB");
var collectionWatchtbl = database.GetCollection<WatchTbl>("Watchtbl");
var collectionUser = database.GetCollection<UserCls>("Users");
var collectionSymbole = database.GetCollection<SymboleCls>("Users");
var list = collectionWatchtbl.AsQueryable().Select(x => new WatchTblCls() {
id = x.id,
userId = x.userId,
.....
});
If you can use the same WatchTbl class and still want to load the full collection to a local List (which is definitely not a good idea):
List<WatchTbl> list = await collectionWatchtbl.Find(x => true).ToListAsync();
Actually I want to delete all documents of a kind in a test procedure but I couldn't do that using DocumentStore.DatabaseCommands.DeleteByIndex command , so I tried to see if I could query those entities , Here's my code :
var store = new DocumentStore { Url = "http://localhost:8080" };
store.Initialize();
var result= store.DatabaseCommands.Query("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag : RunningTables" },null);
result.Results.ForEach(x=>x.WriteTo(new JsonTextWriter(Console.Out)));
It returns no document but when I use RavenDB Studio and execute the same query on Raven/DocumentsByEntityName index.
Then I took a look at my command Url and I realized start=30 so I changed the code as follow :
var result= store.DatabaseCommands.Query("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag : RunningTables",Start=0 },null);
But nothing changed except that now Url doesn't contain start anymore.
What's wrong with my code ?
OK. I've got what was wrong with my Code.I didn't select the default database and there was more than one database in my RavenDB. So I did it like this :
var store = new DocumentStore { Url = "http://localhost:8080" , DefaultDatabase = "MyDbName" };
store.Initialize();
var result= store.DatabaseCommands.Query("Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag : RunningTables" },null);
result.Results.ForEach(x=>x.WriteTo(new JsonTextWriter(Console.Out)));