I am trying to read a row from my MongoDB with the following code
public static void MongoConnection()
{
var connectionString = "127.0.0.1";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "PointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection("OCS.MeterEntity");
BsonDocument documentRead = mongodb.FindOne(new QueryDocument {
{"_id", "4B414D000000011613CD" }
});
But the documentRead is always null and i know the specifik _id exists in the database. What am i doing wrong?
It does connect to the database and the right table.
Seems to be a calling convention:
new QueryDocument( "_id", new ObjectId("4B414D000000011613CD") )
but this should work as well:
new BSONDocument { { "_id", "4B414D000000011613CD" } }
I mannaged to figure it out :)
public static void MongoConnection()
{
var connectionString = "mongodb://localhost";
var mongoClient = new MongoClient(connectionString);
var mongoServer = mongoClient.GetServer();
var databaseName = "PointToPoint";
var db = mongoServer.GetDatabase(databaseName);
var mongodb = db.GetCollection<MongoDBModel>("OCS.MeterEntity");
var mongodbQuery = Query<MongoDBModel>.EQ(x => x._id, "4B414D000000011613CD");
var foundMongoDB = mongodb.FindOne(mongodbQuery);
}
Related
I am using kusto .net SDK to write to kusto database using c#.. I am able to create the table as I please, but I wish to be able to write some rows to the database and populate the columns "a" and "b".. couldn't find an easy way to do this online..
static void Main(string[] args)
{
var KustoClusterConnectionString = $"xxxxxxxxxxxxxx";
var KustoDbName = "userGroup";
var AppId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var TenantId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
var kcsb = new KustoConnectionStringBuilder(KustoClusterConnectionString)
{
InitialCatalog = KustoDbName,
FederatedSecurity = true,
ApplicationClientId = AppId,
ApplicationKey = clientSecret,
Authority = TenantId
};
var tableName = "userGroup";
using (var kustoClient = KustoClientFactory.CreateCslAdminProvider(kcsb))
{
var command =
CslCommandGenerator.GenerateTableCreateCommand(
tableName,
new[]
{
//Tuple.Create("TimeStamp", "System.DateTime"),
Tuple.Create("a", "System.String"),
Tuple.Create("b", "System.String"),
});
kustoClient.ExecuteControlCommand(KustoDbName, command);
}
}
there are several code samples in this repo: https://github.com/Azure/azure-kusto-samples-dotnet
specifically - this project/file: https://github.com/Azure/azure-kusto-samples-dotnet/blob/master/client/HowToDataIngestion/Program.cs
Not able to convert IMongoCollection<MatchDocument> to ObservableCollection<MatchDocument>
MongoClient client = new MongoClient();
var DB = client.GetDatabase("MTR");
var Collection = DB.GetCollection<MatchDocument>("MATCHES");
App.Profiles = new ObservableCollection<MatchDocument>(Collection);
You can use Collection.Find<MatchDocument>(query).ToListAsync():
MongoClient client = new MongoClient();
var DB = client.GetDatabase("MTR");
var Collection = DB.GetCollection<MatchDocument>("MATCHES");
Task<IList<MatchDocument>> doc = await Collection.Find<MatchDocument>(query).ToListAsync();
ObservableCollection<MatchDocument> Profiles = new ObservableCollection<MatchDocument>(doc.Result);
Refer: cannot convert from 'MongoDB.Driver.IMongoCollection<>' to 'System.Collections.Generic.IEnumerable<>'
Basically here's my code which I'm having trouble with. Insanely new to mongoDB and would love to understand how to get values out of a JSON string that is returns in the variable 'line'.
public string get_data()
{
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var cursor = collection.Find("{'movie_name' : 'Hemin'}").ToCursor();
var line = "";
foreach (var document in cursor.ToEnumerable())
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
line = stringWriter.ToString();
}
}
var js = new JavaScriptSerializer();
var d = js.Deserialize<dynamic>(line);
var a = d["movie_name"];
return line;
}
This is the output I get if I return line:
{ "_id" : ObjectId("58746dcafead398e4d7233f5"), "movie_name" : "Hemin"
}
I want to be able to fetch the value 'Hemin' into 'a'.
I know this is not what you're asking for but since you're using the c# driver then I would recommend the following. Assumes you have a c# class corresponding to metacorp collection or at least a serializer that handles it. Hope it helps.
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<MetaCorp>("metacorp");
var m = collection.SingleOrDefault(x => x.Movie_Name == "Hemin"); // Assuming 0 or 1 with that name. Use Where otherwise
var movieName = "Not found";
if(m!= null)
movieName = m.Movie_Name;
You could have your dto class for movie ans just fetch the data from collection:
public class Movie
{
public ObjectId Id { get; set; }
public string movie_name { get; set;}
}
...
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var movies = collection.Find(x=>x.movie_name == "Hemin").ToEnumerable();
I'm trying to perform a very simple mongodb mapreduce with c# 2.3 driver but i'm getting an exception:
The code is:`
string StringDeConexao = "mongodb://10.0.0.211:27017";
MongoClient client = new MongoClient(StringDeConexao);
var servidor = client.GetDatabase("distribuicoes");
var collection = servidor.GetCollection<BsonDocument>("processo");
var mapa = new BsonJavaScript(#"function() {
var chave = this.Natureza;
var valor = {
this.NumeroDoProcesso,
this.Comarca,
this.Natureza,
this.Classe,
this.Assunto.AssuntoPrincipal,
this.Autor.Nome,
this.Autor.TipoDePessoa,
this.CodigoCnaeAutor,
this.Reu.Nome,
this.Reu.TipoDePessoa,
this.CodigoCnaeReu,
count:1
};
emit(chave, valor);
};");
var reducao = new BsonJavaScript(#"function(chave, valores) {
var ObjetoReduzido = {
Natureza: chave,
count: 0
};
valores.ForEach(function(valor) {
ObjetoReduzido.count+= valor.count;
};
return Objeto.Reduzido;
};");
var pesquisa = Builders<BsonDocument>.Filter.Regex("Natureza", new BsonRegularExpression("c[iĆ]vel", "i"));
var option = new MongoDB.Driver.MapReduceOptions<BsonDocument, String>();
option.Filter = pesquisa;
option.OutputOptions = Inline;
var result = collection.MapReduce(mapa, reducao, option);`
It works on mongodb shell.
Thank's for any help.
Your ForEach() is (was) mal-formed and you have (had) trailing semicolons on each of the functions.
Hi I am trying to make a generic method to return a single value from the database
I am not sure where to put the return result, value is returned as a BSON document.I need 1 value from it....
public static string SearchMongoSingleValue(string key, string value, string ducument, string datatable)
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase(datatable);
var collection = database.GetCollection(ducument);
var query = Query.EQ(key, value);
var oneDocument = collection.FindOne(query);
return oneDocument[value];
Thanks
I think you need oneDocument[key] and not oneDocument[value]. Just tested this code:
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
var client = new MongoClient("mongodb://localhost");
var coll = client.GetServer().GetDatabase("local").GetCollection("test1");
var doc = new BsonDocument();
doc.Add("Name","John");
doc.Add("Color","Red");
coll.Insert(doc);
var query = Query.EQ("Name", "John");
var doc2 = coll.FindOne(query);
var value = doc2["Color"];
It returns "Red" allright