mongodb - unable to insert record - c#

I have this code:
public async void SaveAuditLog(AuditLog a)
{
var db = new MongoDBContext();
var o = db.GetMongoDatabase(Common.Common.MongoDbConnectionString);
var audit = o.GetCollection<AuditLog>("AuditLog");
await audit.InsertOneAsync(a);
}
public IMongoDatabase GetMongoDatabase(string connectionstring)
{
MongoClient client = new MongoClient(connectionstring);
return client.GetDatabase("test");
}
this is the connection string from web.config:
<add connectionString="mongodb://localhost:27017" name="mongodb"></add>
when I check the data through robomongo, it does not show me any data inserted.
I have tried the following code as well and no data is inserted:
public async void SaveAuditLog(AuditLog a)
{
var client = new MongoClient(Common.Common.MongoDbConnectionString);
var o = client.GetDatabase("test");
var audit = o.GetCollection<BsonDocument>("AuditLog");
var document = new BsonDocument { {"Test", "test"} };
await audit.InsertOneAsync(document);
}
I am using csharpdriver for mongo with 2.2. What am I doing wrong?

found out that the data is getting inserted in mongodb and there is a bug in robomongo version 0.8.5 itself which does not show collections/documents for mongodb version 3 and above.
ran some scripts (in robomongo) which do return the data:
db.stats()
db.CollectionName.find()
downloaded mongochef and it displayed the data straight away.

Related

C# to upload data to Azure Cosmos DB SQL api

I have following part of code which worked to upload data to CosmosDB Mongo API. Now I am using Cosmos Client to upload document to Cosmos DB SQL API. However, Below lines don't support in SQL api.
var item = objs[i];
var doc = BsonDocument.Parse(item.ToString());
//saving all the documents in cosmos
listTask.Add(collection.ReplaceOneAsync(
filter: new BsonDocument("id", doc["id"]),
options: new ReplaceOptions { IsUpsert = true },
replacement: doc));
Is it possible to replace for SQL API?
private async Task UploadComplete(List<object> objs)
{
double total_cycles = (int)((double)objs.Count / BATCH);
var cycle= 0;
//configuring cosmos connection-SQL
CosmosClient client = new CosmosClient(cosmos);
var database = client.GetDatabase(cosmos_database);
var collection = database.GetContainer(cosmos_collection);
//works for Cosmos DB Mongo API
var item = objs[i];
var doc = BsonDocument.Parse(item.ToString());
//saving all the documents in cosmos
listTask.Add(collection.ReplaceOneAsync(
filter: new BsonDocument("id", doc["id"]),
options: new ReplaceOptions { IsUpsert = true },
replacement: doc));
//Cosmos DB SQL API
//Code here---------
//------------------
}
The equivalent function in the Cosmos .NET SDK is UpsertItemAsync().
I'm assuming here your partition key is /id.
listTask.Add(collection.UpsertItemAsync(
item: doc,
new PartitionKey(doc["id"]));

Inserting document into CosmosDB with C#

I'm trying to insert a new document to a cosmos database running locally with SQLAPI in the Cosmos Emulator. Selecting documents works fine but when I try to insert with below code I get the following error:
Response status code does not indicate success: NotFound (404); Substatus: 1003; ActivityId: 10e20d81-559a-47b3-8eef-021ce4138279; Reason: (Message: {"Errors":["Owner resource does not exist"]}
Code:
async Task<Product> IProductRepository.Add(Product product)
{
var container = cosmosClient.GetContainer("Invertory", "Products");
product.Id = Guid.NewGuid().ToString();
product.Category = new Category() { Name = "test" };
var x = await container.UpsertItemAsync<Product>(product);
return product;
}
It seems that the recourse (database) I try to reach not exists, but when I do a query with the same database and container and with the following code I get the expected results.
async Task<Product> IProductRepository.Get(string Id)
{
var container = cosmosClient.GetContainer("Inventory", "Products");
var iterator = (from p in container.GetItemLinqQueryable<Product>()
where p.Id.Equals(Id)
select p).ToFeedIterator();
return iterator.HasMoreResults ? (await iterator.ReadNextAsync()).First() : null;
}
What am I missing here?
There is a typo in function "IProductRepository.Add". Invertory should be Inventory.

How to get the timestamp from a Firebase database?

I have the following method:
public async void generateTimeStampAsync()
{
FirestoreDb db = FirestoreDb.Create("MY Db project ID");
CollectionReference collection = db.Collection("users");
Query query = collection.WhereLessThan("Born", 1900);
QuerySnapshot querySnapshot = await query.GetSnapshotAsync();
}
How would I use this or a similar method to be able to get a server timestamp from the database? Something similar to the ServerValue.TIMESTAMP in JavaScript. If you could provide any methods that is able to simply return the timestamp of the server to me, that would be great.

How to use SQL query with CosmosDB client in C# .NET Core 2.1 API app

I am trying to use an Azure CosmosDB (former DocumentDB) repository in an API I am creating (I'm quite new to C#). I have managed to get a result with all documents using the client.CreateDocumentQuery method without passing a SQL query to it. However, when I pass a SQL query, program execution hangs and the controller responds with 404. I've tried to add a try-catch around it but I get no exception or anything.
Using Microsoft.Azure.DocumentDB.Core Version 1.9.1.
I've tried many things, other methods and also LINQ, but got nothing to work. If you have a look at this sample method, could you give me an example on how to correctly query and get a result from the document collection? I would really appreciate it!UPDATE: I updated the SQL a bit. Have tried with hard coded parameter and have tested it in the data explorer where it works. Execution seems to freeze on *var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();*
// Document repository
public async Task<IEnumerable<JObject>> GetDocsFromCollectionAsync(string someId)
{
DocumentClient client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);
IDocumentQuery<JObject> documentQuery;
var documentCollectionUri = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
var queryOptions = new FeedOptions { MaxItemCount = -1 };
if (someId.IsNullOrEmpty())
{
// This works
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri,queryOptions)
.AsDocumentQuery();
}
else
{
var query = new SqlQuerySpec(
"SELECT * FROM c WHERE c.someId = #someId",
new SqlParameterCollection(new SqlParameter[] { new SqlParameter { Name = "#someId", Value = someId } }));
// This hangs during execution / returns 404 in the API controller
documentQuery = client.CreateDocumentQuery<JObject>(documentCollectionUri, query, queryOptions)
.AsDocumentQuery();
}
List<JObject> documents = new List<JObject>();
while (documentQuery.HasMoreResults)
{
var feedResponse = await documentQuery.ExecuteNextAsync<JObject>();
documents.AddRange(feedResponse);
}
return documents; // Return documents to API controller
}

How to make my controller work to insert data in mongoDB

I'm trying to insert some data inside my database but I get an error on my HttpPost
here it is :
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<BsonDocument>("Users");
collection.InsertOne<UserInformationViewModel>(info);
return View("_ModalContent");
}
So i get this error
The non-generic method
'IMongoCollection.InsertOne(BsonDocument,
InsertOneOptions, CancellationToken)' cannot be used with type
arguments MVCWithMongo C:\Quentin\Repos\Test\MVCWithMongo\MVCWithMongo\Controllers\UserController.cs 34 Active
I can't figure out why.
If someone could help, would be nice!
I made a modification, i don't have the error anymore but nothing happens.
[HttpPost]
public ActionResult Registration(UserInformationViewModel info)
{
var client = new MongoClient("mongodb://localhost:27017");
var objDatabase = client.GetDatabase("Test");
var collection = objDatabase.GetCollection<UserInformationViewModel>("Users");
collection.InsertOne(info);
return View("_ModalContent");
}

Categories

Resources