Questions tagged [mongodb-.net-driver]

1

votes
2

answer
517

Views

MongoDb use filter to match a list

I have a list of BsonDocument: var list = db.GetCollection(collectionName); var myIds = list.Find(_ => true) .Project(Builders.Projection.Include('_id')) .ToList(); that contains: myIds = '{ { '_id' : 'cc9d9282-c9d2-4cba-a776-ffddsds274d5' }, { '_id' : '2c1ddd82-c9d2-4dda-afr6-d79ff1274d56' },...
DanielV
1

votes
0

answer
359

Views

C# MongoDb deserialization of an abstract sub-document

Prefix: Using .net 4.6.1, C# 7, C# MongoDb 2.5.0 Issue in general: I have a small class which contains a field of an abstract type. [BsonIgnoreExtraElements(true)] public sealed class FatherAlmighty { [BsonId] public ObjectId Id; public MyAbstract Item; } also, this MyAbstract is obviously an abstra...
Ori Refael
1

votes
3

answer
201

Views

Setup method with FindOptions<T> as parameter in UnitTest using Moq

Imagine I have this class: public class MyClass { public string Id { get; set; } public string Name { get; set; } public IList MyOtherClassList { get; set; } } And this method on my service layer which I want to unit-test with Moq and xunit: public IList GetAll() { var options = new FindOptions { Pr...
joacoleza
1

votes
0

answer
67

Views

Unable to save lists to MongoDB using UpdateDefinitionBuilder in C#

I have the following helper function that uses reflection to look at the supplied model, check if any fields are non-null, and overwrite those with new values in MongoDB. It works fine until I try updating a List field. Instead of saving the list as an array to MongoDB, it saves a string value of '(...
ElPresidente
1

votes
1

answer
163

Views

MongoDb with .NET driver add collection jsonschema validation

Is there any way, when creating a collection in mongodb with the .NET driver, to specify a json schema to validate against? I have found documentation on how to set a validator using code, but not how to use a json schema to validate. The reason I'm looking for schema validation in using the .NET dr...
mortb
1

votes
0

answer
316

Views

C# Mongo Driver: Getting Time out, Connection refused by the server (Strange behavior)

I was working with Mongo DB 3.4.2, and I am facing an strange issue when accessing data from my API. The error message says: 'ClassName': 'System.TimeoutException', 'Message': 'A timeout occured after 30000ms selecting a server usingCompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+Are...
Jose Solano
1

votes
0

answer
248

Views

Cosmos DB Mongo API Date Filtering Not Working

I've got the following model inserted into an Azure Cosmos DB MongoDB collection, using the MongoDB .NET Driver. I'm attempting to query on the 'EventDates.EndDate' field and so far, have been completely unsuccessful. My object model is defined as: Event.cs namespace BAH.API.BAHEvents.Models { publi...
Nick DeMayo
1

votes
0

answer
311

Views

Insert items into dictionary in MongoDB via C#

I am unable to translate working Mongo shell commands into C# code. Specifically I would like to insert a new item into a dictionary using either the ArrayOfDocument or ArrayOfArray representation. In the example below I'd like to insert a new grade into my Pupil class. C# Pupil class [BsonId] publ...
SockenLoch
1

votes
0

answer
36

Views

How to undersand **OperationTimeout** for C# MongoDB Driver

Could someone give any guides about OperationTimeout setting? I cannot found any clues for this setting in Mongo-CSHARP-Driver Official Docs. Also, i've searched the Source Code: https://github.com/mongodb/mongo-csharp-driver/search?q=OperationTimeout&unscoped_q=OperationTimeout and seems no usage...
Julian
1

votes
1

answer
219

Views

MongoDB aggregate group on inner child collection and get count

I have a User collection, which further have a 'UserSubscription' collection, which further have 'Subscription > Publication'. I have following User collection in Mongo /* 1 */ { '_id' : 1, 'UserSubscriptions' : [ { '_id' : 1, 'Subscription' : { '_id' : 1, 'Publication' : { '_id' : 1, 'Code' : '1MM...
Anil D
1

votes
1

answer
217

Views

C# Mongo Driver error: Cannot deserialize a 'Int32' from BsonType 'Document'

Following MongoDB query run fine on Robo3T 1.2 and return correct 'count'. db.runCommand( { aggregate: 'User', pipeline: [ {$unwind: '$UserSubscriptions'}, {$group: { _id: '$_id', codes: {$addToSet: '$UserSubscriptions.Subscription.Publication'} }}, {$unwind: '$codes'}, {$group: { _id: '$codes', cou...
Anil D
1

votes
0

answer
160

Views

Does the MongoDB C# driver support Joins of this manner?

I have two classes Person and Animal using System; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace MongoTesting.Documents { public class Person { [BsonId] [BsonRepresentation(BsonType.String)] public Guid PersonId { get; set; } = Guid.NewGuid(); public Guid PetId { get; se...
KDecker
1

votes
0

answer
42

Views

Mongodb driver deadlock in asp.net core

I have simple asp.net WebApi project with two controllers. First controller use System.Linq and has a deadlock under heavy loading. Second use MongoDB.Driver.Linq and work great. I used ab -c 10 -n 200000 -p post -H 'Content-Type: application/json' -T 'application/json' 'http://localhost:1989/api/...
1

votes
1

answer
45

Views

MongoDB Grouping and Project Custom Fields

I am stuck with MongoDB grouping and project custom fields. I have the following collection: { 'DescId' : '1', 'Desc' : 'Testing', 'ParentId' : 'null', 'Order' : 1.0, 'Type' : 'A', 'Parent' : null } { 'DescId' : '1.1', 'Desc' : 'Testing Child 1', 'ParentId' : '1', 'Order' : 1.0, 'Type' :...
Vani Kulkarni
1

votes
1

answer
87

Views

Invalid JSON number '2L'. shard key being serialized to number but defined as string?

Exception: System.FormatException: Invalid JSON number '2L'. at MongoDB.Bson.IO.JsonScanner.GetNumberToken(JsonBuffer buffer, Int32 firstChar) at MongoDB.Bson.IO.JsonScanner.GetNextToken(JsonBuffer buffer) at MongoDB.Bson.IO.JsonReader.PopToken() at MongoDB.Bson.IO.JsonReader.ReadBsonType() at Mongo...
Kdog
1

votes
0

answer
73

Views

MongoDB self join(aggregation) of collection with parent references

Hello I have this collection, with parent references, I need to do self join on this collection, so that output will contain the children to maximum depth in one document and also get the output based on 'Type' field. { 'DescId' : '1', 'Desc' : 'Testing', 'ParentId' : 'null', 'Order' : 1.0, 'Ty...
Vani Kulkarni
1

votes
1

answer
92

Views

MongoDB storing one day before than actual date [duplicate]

This question already has an answer here: Mongodb saves one day less - Time Zone Issue 1 answer I am facing one issue to store the actual date(01/08/2018) that what I passed from model. My document is stored successfully but MongoDB store the one day before than what I passed in model. Here I am pa...
Dipak Delvadiya
1

votes
1

answer
237

Views

Creating a database and collection programmatically for Azure Cosmos DB via Mongo DB .NET Driver

I am using the .NET MongoDb driver and Azure Cosmos DB Emulator. I am trying to create a database and collection on startup of a dotnet core Web Api project. I am running the following code within the ConfigureServices function in Startup.cs. var connectionString = databaseConfig.GetValue('connectio...
Prabu
1

votes
0

answer
53

Views

Issue with Geonear in latest mongo c# driver

have a .NET Application that uses a MongoDB so I am using mongo c# driver. Current version I am using is 1.9.2. I am trying to update this to latest C# mongodb driver - 2.7.0. I have had to make numerous code changes so far for breaking changes. I am having an issue getting the below to work 1.9.2...
Ctrl_Alt_Defeat
1

votes
1

answer
56

Views

Checking if a part of a text field if is contained in an array of strings

I have an array of search terms(userSearchTerms) that I want to filter in the Users collection(users = _id + name, ex: Bill Gates, Paul Allen, Satya Nadella). userSearchTerms = string[] {'Bil', 'Pau', 'Saty'}; In mongodb, I managed to query like this: db.users.find({ name: { $in: [ /Bil/i, /Pau/i, /...
Misi
1

votes
0

answer
169

Views

Is it safe to use MongoDB ClientSessions & Transactions in C# async code?

From the docs Read isolation consistency - Sessions (emphasis mine) To provide causal consistency, MongoDB 3.6 enables causal consistency in client sessions. A causally consistent session denotes that the associated sequence of read and acknowledged write operations have a causal relationship that i...
Binary Worrier
1

votes
0

answer
227

Views

Mongodb FindOneAndUpdate in .NET not thread safe?

I'm trying to create a unique counter table. To update the counter in the table I tried using FindOneAndUpdate. At first everything seem to work as planned so I figured I would stress test it. I created a process that gets a counter 20,000 and executed that counter on 5 threads. Sure enough, I end u...
jbassking10
1

votes
0

answer
18

Views

Schema changes from int to List of Int in MongoDB

My requirement is to change Mongodb schema for a property of type integer to list of integer. In production, Mongodb has already data in integer format. I want to support data in both format i.e. integer as well as list of integer. My Model was like below Public class TObj { public string Id {get...
Manish Jain
1

votes
0

answer
24

Views

mongodb c# addShardTag

Is there a way to add a Shard Tag (as found in addShardTag ) for shell access) via c#? I have a server program which creates collections dynamically. Each collection has thousands of records from IOT devices and I would like to keep collections to different shards using shard tags. As the collectio...
Muthu
1

votes
0

answer
32

Views

Filtering in mongo by interface

I have a mongo collection that I want to type to an interface. It should be able to contain multiple concrete types, all of which implement this interface. However when making queries if I use the interface it tells me that it cannot find serialization information. Sample code: var collection = data...
Chris
1

votes
0

answer
31

Views

Project array item from document

imagine I have the following class setup which I store in my MongoDB collection: public class Person { public ObjectId _id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List Children { get; set; } } So a singular document inside of the collection mig...
Manuel Zelenka
1

votes
1

answer
76

Views

Find/Count documents by partial _id value in MongoDB

I want to find documents in my collections via partial _id values that I enter in a GUI application. After some searching I found out that I could at least find documents by it's partial id using the following filter: { $where: 'this._id.str.match(/5a.*/)' } (where 5a is the partial id value the u...
TorbenJ
1

votes
1

answer
127

Views

MongoDB C# driver - Serialize collection to interface

Due to environment restrictions at work I'm implementing a rough Event Sourcing store in MongoDB. I'm trying to get a list of IClientEvents from Mongo like so: var events = await _db.GetCollection('ClientEvents').FindAsync(c => c.ClientId == clientId); I get the following exception when I run the ab...
LukeP
1

votes
0

answer
17

Views

Unable to connect to MongoDB Replica Set from other server using robo3T and in C#

I have installed mongodb Replica Set, in the file mongod.conf has added BIND_IP as below net: port: 27017 bindIp: 127.0.0.1, 100.0.192.68 When I use robo3t to connect the 'replica set' type the error, but when connected to the 'Direct Connection' is successful. error TYPE='Replica Set Connection str...
Joyce K
1

votes
0

answer
43

Views

MongoDb driver 2.7 query join

I'm trying to join two simple collection using the mongoDbDriver linq, but I'm having some strange problem on when trying to execute the resultant query. I tried to replicate the query using normal Linq so executing everything in memory and I'm not having any problem. Inside the constructor of Pre...
Davide Quaglio
1

votes
0

answer
146

Views

C# MongoDB IAsyncCursor Explain

I am currently having a text index in my data. I am performing a regex search and I want to make sure that the correct index is used. In the mongo shell I just used explain but how could I use explain in the C# driver? Here's how I perform my query: public async Task Find(string fileName) { var filt...
Kaloyan Manev
1

votes
0

answer
47

Views

How to update document in NoSQL database like mongo db?

We are using mongo dB in our application with C# as language. Currently we are loading entire document as object in C#. Make changes to document which happens in memory, and look like very costly. and then call ReplaceOrSave method on mongo collection. Is there a way in mongoDB, where can just updat...
Krunal Parmar
1

votes
1

answer
44

Views

NET Core MongoDb Update/Replace exclude fields

I'm trying to complete a general repository for all of the entities in my application. I Have a BaseEntity with property Id, CreatorId and LastModifiedUserId. Now I'd like to Update a record in a collection, without having to modify the field CreatorId, so I have (from the client) an Entity valorize...
Davide Quaglio
1

votes
0

answer
56

Views

Cannot convert to type 'MongoDB.Bson.Serialization.IBsonSerializer`1[System.String]'

I'm using the mongoDB driver for C# and I'm having issues trying to do some queries due to the Serialization/Deserialization. As far as I could understand I'm not able to serialize an Int32 field to string. System.ArgumentException: Object of type 'US.EndPointTests.AdditionalFunctionalities.TestingO...
DiegoMG
1

votes
1

answer
44

Views

MongoDB C# Driver Find not throwing System.FormatException Deserialization error and runs successfully

I am using latest c# mongo driver in my .net core 2.0 app. I have this error in my code Cannot deserialize a 'String' from BsonType 'Int64'.. But mongo query doesn't threw any exception. Here is the find method in my repository. /// /// find entities /// /// expression filter /// collection of en...
Ghazanfar Khan
1

votes
1

answer
86

Views

MongoDb c# driver enum mapping

I have Enum: public enum SomeType { TypeA, TypeB, TypeC } but in MongoDB i would like this map to: type_a type_b type_c I'm using EnumRepresentationConvention(BsonType.String) I tried: public enum SomeType { [BsonElement('type_a')] TypeA, [BsonElement('type_b')] TypeB, [BsonElement('type_c')] Type...
Jakub Dropia
1

votes
1

answer
98

Views

How to delete many documents in a partitioned collection in Azure CosmosDB using MongoDB API

Consider the following document type class Info { public string Id { get; set; } public string UserId { get; set; } // used as partition key public DateTime CreatedAt { get; set; } } I've created a collection using this var bson = new BsonDocument { { 'shardCollection', 'mydb.userInfo' }, { 'key',...
hansmaad
1

votes
2

answer
25

Views

Retrieve MongoDB collections as a sequence of `IMongoCollection<T>` in .NET driver

IMongoDatabase.ListCollections return a cursor over BsonDocument. Why doesn't it return a cursor over IMongoCollection instead? I was trying to write a generic GetCollection method to retrieve the collection given just the document type, something like this: private IMongoCollection GetCollection()...
is.cattabiani
1

votes
0

answer
27

Views

How to Regex Match by keyword in MongoDB and sort the results by most relevant results using C#?

I'm regex searching a {keyword} against a field [Name] from one of the collections [Brands] of Mongo DB using C#. And the result items would be sorted by the textMatchScore by descending. The result looks good but the format looks pretty weird. The expected results would be like this. [ { 'id': '5c...
ske
1

votes
0

answer
34

Views

Why is my mongo .net driver code not concurrency safe?

WiredTiger is supposed to handle document level concurrency. Is the Mongo .Net Driver compatible with this locking mechanism ? Why is this code not giving me the right result : public class MyClass { public int Id { get; set; } = 1; public List Prop { get; set; } } public class MyClassRepository :...
Benjamin Lalonde

View additional questions