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
});
Related
So with the latest update with Elastic Search 6, The C# Client was also upgraded too. But i can't figure out how to write this code the new way with the new Client Nest 7. I just need to rewrite this code
var indexExists = Client.IndexExists(CurrentAliasName).Exists;
Client.Alias(aliases => {
if (indexExists)
{
var oldIndices = Client.GetIndicesPointingToAlias(CurrentAliasName);
var indexName = oldIndices.First().ToString();
//remove alias from live index
aliases.Remove(a => a.Alias(CurrentAliasName).Index("*"));
}
return aliases.Add(a => a.Alias(CurrentAliasName).Index(CurrentIndexName));
});
The APIs have been moved into API groupings
var client = new ElasticClient();
var CurrentAliasName = "alias_name";
var CurrentIndexName = "index_name";
var indexExists = client.Indices.Exists(CurrentAliasName).Exists;
client.Indices.BulkAlias(aliases =>
{
if (indexExists)
{
var oldIndices = client.GetIndicesPointingToAlias(CurrentAliasName);
var indexName = oldIndices.First().ToString();
//remove alias from live index
aliases.Remove(a => a.Alias(CurrentAliasName).Index("*"));
}
return aliases.Add(a => a.Alias(CurrentAliasName).Index(CurrentIndexName));
});
You can also reference Nest.7xUpgradeAssistant package and keep using the same methods as in 6.x to help with the move to 7.x. You'll get compiler warnings with messages to indicate where the new API methods are located.
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();
I am trying to write a method which would return all the Book documents from the MongoDB to my mvc application. First, I connect to database, retrieve collection and convert that collection into Json file. Next I create a list which has couple fields specified (name, author, etc.) using serializer i try to deserialize it into list and using a for loop return the list of books. Sadly I get error in the return line (convertion error). Any suggests are welcomed!
public List<Book> getAllBooks()
{
var mongoClient = new MongoClient("mongodb://localhost");
var database = mongoClient.GetDatabase("SearchForKnowledge");
var coll = database.GetCollection<BsonDocument>("Book");
coll.ToJson();
List<Book> collection = new List<Book>();
JavaScriptSerializer js = new JavaScriptSerializer();
collection = (List<Book>)Newtonsoft.Json.JsonConvert.DeserializeObject(coll.ToString());
for (int i = 0; i < collection.Count(); i++)
{
return collection[i];
}
}
well, you should try simpler way:
// add this using first
using MongoDB.Driver.Linq;
var coll = database.GetCollection<Book>("Book").AsQueryable<Book>();
And than you can do anything, e.g:
var someBooks = coll.Where(b => b.Year == 2014).Skip(0).Take(10).ToArray();
PS: You need to check out this tutorial: https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/tutorial/use-linq-queries-with-csharp-driver.html
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
I'm Using the .net Google Plus API and i want to get the list of activities of a specified profile(page/user..).
I have this code which i get it online
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = GoogleIdentifier;
provider.ClientSecret = GoogleSecret;
ActivitiesResource.Collection collection = new ActivitiesResource.Collection();
var service = new PlusService();
service.Key = GoogleKey;
ActivitiesResource.ListRequest list = service.Activities.List(ProfileID, collection);
ActivityFeed activityFeed = list.Fetch();
int count = activityFeed.Items.Count;
on this line:
ActivityFeed activityFeed = list.Fetch();
I get the following error:
An item with the same key has already been added.
The requested keys was invalid. Just Put the right ClientSecret & ClientIdentifier.