In sqlite I would do, But how in mongodb c# - c#

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.

Related

How to use multiple filters in a MongoDb find query using C#

I have this query which works fine in datagrip
test> db.getCollection("comments").find({status: {$ne: "APPROVED"},storyID: {$regex: "bbjfn-*"}})
I'm just wondering how to achieve the same thing in C# using the MongoDB Driver 2.13.1
IMongoDatabase database = MongoClient.GetDatabase(Program.Settings.MongoDB.Database);
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("comments");
var filter = Builders<BsonDocument>.Filter.Eq("status", new BsonDocument("$ne", "APPROVED")) &
Builders<BsonDocument>.Filter.Eq("storyID", new BsonDocument("$regex", "bbjfnfn-*"));
var results = await collection.FindAsync(filter);
Doesn't work.. what am I doing wrong?
You can set filter with BsonDocument object as below:
FilterDefinition<Store> filter = new BsonDocument
{
{ "status", new BsonDocument("$ne", "APPROVED") },
{ "storyID", new BsonDocument("$regex", "bbjfn-*") }
};
OR
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Ne("status", "APPROVED") & builder.Regex("storyID", "bbjfn-*");
FYI, you can use MongoDB Compass to export Query to C# Language.

Create document not working - C# DocumentDB/CosmosDB

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

Dynamics CRM 2016 c# use id of not yet existing entity

for my project, I have to create multiple Quotes and add products to it.
For performance reasons (about 5000 quotes) I am using "ExecuteMultipleRequest()".
This is about what I've got:
var quote = new Quote
{
QuoteNumber = "123",
Name = "test123",
PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, Pricelevel.Id),
CustomerId = new EntityReference(Account.EntityLogicalName, Customer.Id),
};
_requests.Requests.Add(new CreateRequest { Target = quote });
var quoteDetail = new QuoteDetail
{
QuoteId = new EntityReference(Quote.EntityLogicalName, quote.Id),
ProductId = new EntityReference(Product.EntityLogicalName, product.Id),
IsPriceOverridden = true,
PricePerUnit = new Money(20),
Quantity = Convert.ToDecimal(5),
};
_requests.Requests.Add(new CreateRequest { Target = quoteDetail });
My problem is the quote.Id. I know it is empty until the server processes the request and creates the quote.
Is there a way to tell the server it should use the quotes new id for the quotedetail?
Or is my only way to create the quote itself and then create all details?
What can I do to increase performance if I have to do it this way?
Instead of sending CreateRequests explicity, you could change your code to use the OrganizationServiceContext, which locally tracks changes to objects before submitting them to CRM.
When using the OrganizationServiceContext, you can use AddRelatedObject to both add an object and link it to another one:
Adds a related entity to the OrganizationServiceContext and creates
the link that defines the relationship between the two entities in a
single request.
Alternatively you could manually call AddObject and AddLink.
You final code would look similar to the following:
using (var context = new OrganizationServiceContext(_serviceProxy))
{
var quote = new Quote
{
QuoteNumber = "123",
Name = "test123",
PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, pricelevel.Id),
CustomerId = new EntityReference(Account.EntityLogicalName, customer.Id),
};
context.AddObject(quote);
var quoteDetail = new QuoteDetail
{
ProductId = new EntityReference(Product.EntityLogicalName, product.Id),
IsPriceOverridden = true,
PricePerUnit = new Money(20),
Quantity = Convert.ToDecimal(5),
};
context.AddRelatedObject(quote, new Relationship("quote_details"), quoteDetail);
context.SaveChanges();
}

MongoDB C# Driver 'Cursor not found' with Linq query

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

MongoDB C# Driver Unable to Find by Object ID?

Using MongoDB C# driver (http://github.com/samus/mongodb-csharp), seems that I'm unable to get the data by ObjectId. Below the command that I'm using:
var spec = new Document { { "_id", id } };
var doc = mc.FindOne(spec);
I also tried this:
var spec = new Document { { "_id", "ObjectId(\"" + id + "\")" } };
var doc = mc.FindOne(spec);
Both return nothing. Meanwhile, if I query it from the mongo console, it returns the expected result.
My question is, does that driver actually support the lookup by ObjectId?
Thanks..
It does support fetching by object ID. Your id variable should be an Oid. Is it the correct type?
Here is a complete program that will
Connect to Mongo
Insert a document
Fetch the document back using its ID
Print the document's details.
// Connect to Mongo
Mongo db = new Mongo();
db.Connect();
// Insert a test document
var insertDoc = new Document { { "name", "my document" } };
db["database"]["collection"].Insert(insertDoc);
// Extract the ID from the inserted document, stripping the enclosing quotes
string idString = insertDoc["_id"].ToString().Replace("\"", "");
// Get an Oid from the ID string
Oid id = new Oid(idString);
// Create a document with the ID we want to find
var queryDoc = new Document { { "_id", id } };
// Query the db for a document with the required ID
var resultDoc = db["database"]["collection"].FindOne(queryDoc);
db.Disconnect();
// Print the name of the document to prove it worked
Console.WriteLine(resultDoc["name"].ToString());
var spec = new Document { { "_id", ObjectId.Parse(id) } };
var doc = mc.FindOne(spec);

Categories

Resources