FAQ Database Discussion Community


get all documents from mongoDB collection

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I need to retrieve all the documents that are in my collection in MongoDB, but I cannot figure out how. I have declared my collection like this private static IMongoCollection<Project> SpeCollection = db.GetCollection<Project>("collection_Project"); and I followed what is explained in this MongoDB tutorial. I ajusted it for my needs, like:...

BsonClassMapSerializer already registered for AbstractClassSerializer

mongodb-csharp
I'm using the Mongo c# driver 2.0 and am running into BsonSerializer registration issues when registering AbstractClassSerializers for my Id value objects. MongoDB.Bson.BsonSerializationException: There is already a serializer registered for type HistoricalEventId. When I peek into the BsonSerializer I'm seeing that a BsonClassMapSerializer is already registered for my type. I'm...

Use of MongoDB in a Windows Service

c#,.net,mongodb,database-connection,mongodb-csharp
I need to write a Windows Service in C# that stores data to a MongoDB database. My current code is: var databaseName = MongoUrl.Create(connectionString).DatabaseName; var server = new MongoClient(connectionString).GetServer(); _mongoDatabase = server.GetDatabase(databaseName); var collection = _mongoDatabase.GetCollection<IMessageWrapper> ("Test"); collection.Save(test); When using SQL databases it is usually very expensive to open a...

How to prevent BSON deserialization instantiating members in a class?

deserialization,mongodb-csharp,bson
I have a class that instantiates it's own internal objects and changes internal properties on them which aren't serialized. One for example is setting the parent object. How do you prevent the BSON driver from instantiating these particular members on a class, since the main class for the document already...

Mongodb query documents where nested array is equal or subset of fixed array

c#,arrays,mongodb,subset,mongodb-csharp
I keep banging my head against the wall trying to solve the following problem (I'm using the new c# 2.0 driver): The idea is to return all docs where the nested array is equal or a subset of a fixed array. Example: Fixed array: [ "A", "B", "C" ] container...

Ensure utilization of compound index with lambda

c#,mongodb,lambda,mongodb-csharp
We query a schools collection by two fields using the mongocsharpdriver (v2.0.0) API like: db.GetCollection<School>("schools").Find(x => x.City == myCity && x.State == myState); Will the order of the fields listed in the lambda expression generate a query to leverage a compound index with the same order: { "city": 1, "state":...

Unwind then Group aggregation in MongoDB C#

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm having some trouble with the new C# 2.0 MongoDB driver and the aggregation pipeline. Basically, I'm trying to return the most popular elements within an array field on the object. The field type is: IList<string> FavouritePlaceIds { get; set; }. I have the following MongoDB aggregation which is working...

MongoDB C# Driver 2.0 - Update document

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm currently upgrading my code to MongoDB C# driver 2.0 and I'm having issues upgrading the code to update documents. using the old version I was able to do something like this: MyType myObject; // passed in var collection = _database.GetCollection<MyType>("myTypes"); var result = collection.Save(myObject); I'm struggling to find a...

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0
We are using the MongoDB C# driver to insert a collection of records using InsertManyAsync. We currently have code that iterates the entire collection after InsertManyAsync returns, confirming that the ID's are populated. I would expect that the driver takes care of this already, but I have not found documentation...

Understanding the changes in Mongodb new c# driver (async and await)

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0
The new c# driver is totally async and in my understanding twists a little bit the old design patterns such as DAL in n-tier architecture. In my mongo DALs I use to do: public T Insert(T entity){ _collection.Insert(entity); return entity; } this way I can get the persisted ObjectId. Today,...

Update complex types without wrapping

c#,mongodb,mongodb-csharp
When writing new documents or updating existing ones, the mongodb-c-sharp-driver outputs generic bson/json for non-primitive types "myList" : [ {"value" : "..."}, {"value" : "..."} ] When using the Update.Set() statement however, the driver wraps the actual data with type info "myList" : { "_t" : "System.Collections.Generic.List`1[[Models.MyModel, Common]]", "_v" :...

Inserting object into embedded document

c#,mongodb,mongodb-csharp
I'm trying to learn the mongoDB driver for C#. First time using the driver on a NoSQL database. I'm trying to insert an object inside a collection inside another object but cant get it to work. I have been searching for examples with no luck. Current Code : public class...

MongoDB .Net driver 2.0 Builders Filter (field to array comparison)

mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
I need to get all usernames from "followingList.username" and compare with posts' usernames, if there any match need to add that one to an array. Person Model { "_id" : ObjectId("554f20f5c90d3c7ed42303e1"), "username" : "fatihyildizhan", "followingList" : [ { "_id" : ObjectId("55505b6ca515860cbcf7901d"), "username" : "gumusluk", "avatar" : "avatar.png" }, { "_id"...

How to cast mongo collection to interface C#

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I have a repository with signature: public Task<IList<IFoo>> GetList() { } How do I cast mongoDb collection to this interface? (MongoDb Driver 2.0) public Task<IList<IFoo>> GetList() { Task<List<Foo>> foo = this.database.GetCollection<Foo>("Foo").Find(e => true).ToListAsync(); return foo ; // ?? somehow cast Task<List<Foo>> to Task<IList<IFoo>> } also, this code bothers me collection.Find(e...

MongoDB Map Property 'new' in findAndModify using FindOneAndUpdateOptions class C# Driver

c#,mongodb,mongodb-csharp
I'm trying to implement a getNextSequence function for mongoDB explain on this Link I'm using the lattes C# driver but I not sure how to map the new : true property in the FindOneAndUpdateOptions MongoDB Code function getNextSequence(name) { var ret = db.counters.findAndModify( { query: { _id: name }, update:...

MongoDb c# bad unknown operator exception

c#,mongodb,mongodb-csharp
I execute the following query : { $query : { "userId" : 11851, "p2l.listId" : 38882, "isDeleted" : false }, $orderby: { email: 1}, $skip: 0, $limit:100 } via the following code : BsonDocument document = BsonSerializer.Deserialize<BsonDocument>(queryString); QueryDocument queryDoc = new QueryDocument(document); var toReturn = collection.Find(queryDoc); return toReturn.ToList(); and I...

Using GridFS with official C# driver in MonoDevelop

c#,mongodb,monodevelop,mongodb-csharp,freebsd
I am using MonoDevelop on PC-BSD 10.1 and working with MongoDB 3.2. I downloaded MongoDB.Driver (+Bson& Core) from Nuget. I can do basic reads and writes and was trying to get GridFS working by following what seems to be the most current example from StackOverflow: MongoDB GridFs with C#, how...

Mongo c# difference between implementing IBsonDocumentSerializer and registering BsonClassMap

mongodb,mongodb-csharp
The Title says it all I'm trying to custom serialize a POCO that looks like this public class myClass{ anotherClass entity List<averydifferentclass> entities String Group String SubGroup } each of the above properties will need separate custom mapping/serialization What's the best way to do this? Thanks...

MongoDB 2 - query array without hardcoding name

c#,mongodb,mongodb-csharp
I have an Issue entity with contains a List of Guids named AssignedTo. For one ID, I need to retrieve all issues with that ID inside AssignedTo list/array So far I've managed doing this with: var filter = Builders<Issue>.Filter.Eq("AssignedTo", id.ToString()); return await Collection.Find(filter).ToListAsync(); but I do not want to hardcore...

How to create a class for a MongoDB collection that is not mine?

c#,linq,mongodb,mongodb-query,mongodb-csharp
I'm new to MongoDB and having some issues. Following this easy guide here (http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver) but I'm instead connecting to a database that I did not personally create. So when the examples include something like: var collection = database.GetCollection<Entity>("entities"); it doesn't work for the actual database i'm connecting to because I...

Get generated script in MongoDB C# driver

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I am using MongoDB.Driver 2.0.0. Is there any way to see a generated script from linq to MongoDB? For example my query is like: IFindFluent<ProductMapping, ProductMapping> findFluent = Collection.Find( x => hashValues.Contains(x.UrlHash) && x.ProductTopic == topicId); How would this (or more complex queries) be represented in the MongoDB shell?...

Documents not expiring using TTL in mongodb 3.0 (.Net driver 2.0)

mongodb,mongodb-csharp,mongodb-csharp-2.0
I have the following code. The EnsureIndexes is called by the constructor to make sure that a TTL index has been created on the _expireAt field. Then when a document is inserted by calling the AddOrUpdateItem method, it adds a future date to the _expireAt field. However, that date passes...

Get all records with inner record from last month - MongoDB C# SDK

c#,mongodb,mongodb-csharp
I'm trying to get all the users that had any kind of activity in the last month from my MongoDB database, using C# SDK. My User record contains a list of statistical records (as ObjctId) with creation date. public class UserRecord { private string firstName; public ObjectId Id { get;...

Initialize MongoClient with MongoClientSettings in C#

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm trying to initialize the MongoClient from the Mongo 2.0 driver as follows: MongoClientSettings settings = new MongoClientSettings(); settings.WaitQueueSize = int.MaxValue; settings.WaitQueueuTimeout = new TimeSpan(0,2,0); settings.MinConnectionPoolSize = 1; settings.MaxConnectionPoolSize = 25; settings.Server = new MongoServerAddress("mongodb://localhost"); client = new MongoClient(settings) However, when I now try to insert a document with this...

Update all properties of object in MongoDb

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0
I'm using the MongoDB .Net driver in my project. I want to update all of the properties of my object that is stored in MongoDB. In the documentation, update is shown like this: var filter = Builders<BsonDocument>.Filter.Eq("i", 10); var update = Builders<BsonDocument>.Update.Set("i", 110); await collection.UpdateOneAsync(filter, update); But I don't want...

MongoDB. Index was out of range

c#,mongodb,mongodb-csharp
I keep having this error as I try to retrieve thousands of documents from the collection. index was out of range. must be non-negative and less than the size of the collection. parameter : Index Here is my code as I query the documents: MongoCollection<Book> collection = PDatabase.GetCollection<Book>("books"); List<IProduct> products...

Multiple composite keys

mongodb,mongodb-csharp
This is my entity: { name: "", list: [{ a: 1, b: 1 }] } I want to create two index, one by name and other for a and b together. Example: trying to insert a=1 and b=1 twice must throw an error. My mongodb driver is 2. For name...

Query with $in operator and large list of Ids

mongodb,mongodb-csharp
I have a pretty large number of document Ids to iterate through (say 5k-10k). The $in operator doesn't limit that number starting from mongodb version 2.6. Earlier versions had a combinatorial limit of 4 mio. That said, does it make sense at all to do something like that in mongodb...

How do I search nested criteria using MongoDB c# driver (version 2)?

c#,linq,mongodb,mongodb-csharp,mongodb-csharp-2.0
I have a collection of documents that can contain criteria grouped into categories. The structure could look like this: { "Name": "MyDoc", "Criteria" : [ { "Category" : "Areas", "Values" : ["Front", "Left"] }, { "Category" : "Severity", "Values" : ["High"] } ] } The class I'm using to create...

Query deeply embeded documents in MongoDB with C# driver

c#,mongodb,mongodb-csharp
This is just an example code... I have managed to get to the third embeded document using .$ , but not further... How do I query the fourth nested part(article headings)? { "bookTitle": "MongoDB", "_id": ObjectId("530dea1d2dbf280000533b60"), "bookChapters": [{ "chapterTitle": "chapterTitle", "_id": ObjectId("530dea1d2dbf280000533b61"), "chapterArticles": [{ "articleTitle": "articleTitle", "_id": ObjectId("530dea1d2dbf280000533b62"), "articleHeadings": [{...

Is anyone able to connect to MongoDB using the new mongodb .net 2.0 client?

c#,mongodb,mongodb-csharp
I installed MongoDB.Driver 2.0 from nuget published 4/2/2015. I also installed MondgoDB via chocolatey version 2.4.7. I created a test app in VS2013, as follows: var client = new MongoClient(); var database = client.GetDatabase("foo"); var foo = database.GetCollection<BsonDocument>("bar"); From what I have read in the docs, this should be sufficient...

MongoDB Custom Serializer to avoid _t being added collection, throws ReadEndArray Error?

c#,mongodb,serialization,mongodb-csharp
Situation: Language: C# using the C# Driver I have a model that contains a List as a property. That List can contain one of 3 different models that all inherit the BaseModelClass. To assist in serialization of this situation Mongo adds _t to identify which of the models is actually...

oData's skip() and top() pulling entire record set before filtering

mongodb,asp.net-web-api,odata,mongodb-csharp,asp.net-web-api-odata
i have an oData enabled web api function [EnableQuery()] public IQueryable<StoreCommand> Get() { return _storeCommandService.GetAllStoreCommands().AsQueryable(); } the service layer calling Mongodb based Repository pattern's implementation. public IEnumerable<StoreCommand> GetAllStoreCommands() { return _uow.StoreCommands.GetAll(); } where GetAll is implemented in Repository layer like public IList<TEntity> GetAll() { return _collection.FindAllAs<TEntity>().ToList(); } where _collection is...

Run Through a MongoDB collection in reverse mode

c#,.net,mongodb,mongodb-csharp
I have a collection "collection_Save" in mongoDB that contains documents that are used to save the operations that occur on others documents in an other collection. They are listed by order of creation in the database. In order to reverse those operations I need to run through the collection from...

Serialize a Dictionary in the “Document” representation, when the key is an Enum

c#,.net,mongodb,mongodb-csharp
I am attempting to write "MyClass" below to a Mongo collection: public enum MyEnum { A, B, C }; public class MyClass { [BsonId(IdGenerator = typeof(StringObjectIdGenerator))] public string Id { get; set; } [BsonDictionaryOptions(DictionaryRepresentation.Document)] public Dictionary<MyEnum , MyOtherClass> Items { get; set; } } public class MyOtherClass { public string...

MongoDB, C#, QueryFailure flag was not master and slaveOk=false

asp.net-mvc,mongodb-csharp
I have a site that has been running perfectly fine for months, and now, all of a sudden, nothing works. The site is done with MVC 5 and is use MongoDB for storage. My best guess is that the MongoDB host is messing around, and that's causing the problem, but......

What does "new BsonValue[]{x,y,z} do?

mongodb,mongodb-csharp
This code is used with the C# driver to select items from a document of items that have a location field value in the range of location id values, I am just providing it as an example: var locations = new BsonValue[] { 1, 2, 3, 4 }; var data...

How to select documents by field range of values in MongoDB C# driver?

c#,mongodb,mongodb-csharp
I have a collection named Items. Documents in the Items collection have a field named "LocationId." How do I select, and bring back to server, all Item documents that have a LocationId that matches a list, array, etc (whatever collection you prefer) of Location Ids? tl:dr for clarity: 1. Have...

mongodb 2.0 query by discriminator

c#,mongodb,mongodb-csharp
Given the following model [BsonDiscriminator(RootClass = true)] [BsonKnownTypes(typeof(Employee), typeof(Contractor)] public class Person { public ObjectId Id {get;set;} public string Name {get;set;} } public class Employee : Person { public double Salary {get;set;} } public class Contractor : Person { public double DailyRate {get;set;} } with the legacy driver I can...

MongoDB .Net driver 2.0 Pull (remove element)

c#,mongodb,mongodb-csharp
Can you help me to run correctly "Pull (remove)" with 2.0 driver. I have a collection like this and I want to remove first follower named as fethiye by follower field. { "_id": ObjectId("554e05dfc90d3d4dfcaa2aea"), "username": "bodrum", "followerList": [ { "_id": ObjectId("554e0625a51586362c33c6df"), "follower": "fethiye", "avatar": "fethiye.png" }, { "_id": ObjectId("554e0625a51586362c33c6df"), "follower":...

MongoDB C# 2 Driver — Cannot deserialize 'String' from BsonType 'Double'

c#,mongodb,mongodb-csharp
I am new to MongoDB. I am trying to retrieve all entries in a lookup Collection. I am receiving the following error: {"An error occurred while deserializing the Symbol property of class Stock.Models.StockLookup: Cannot deserialize a 'String' from BsonType 'Double'."} This is the code that I am receiving the error...

Encoding issue with string stored in database

c#,unicode,encoding,mongodb-csharp
I have an encoding problem. I have text in my MongoDB that is wrongly encoded. The source file of the texts in my db is encoded in ISO-8859-1. Now, in viewing it in my db, some characters were broken (become '�'). Currently, in retrieving text from db i tried the...

MongoDB: Querying for a referenced document

c#,.net,mongodb,mongodb-csharp
I am new to MongoDB and I read the MongoDB documentation. I have following structure: - public class User { [BsonId] public long UserId { get; set; } public string LoginId { get; set; } public string Password { get; set; } public List<string> Gateways { get; set; } }...

In MongoDb, how can you set a value on an object in a array property?

c#,mongodb,mongodb-csharp
My goal is to put a "deleted at" timestamp on specific object in an array of a document. If the document looks like this: { "subdoc": [ { "key": 1, "value": "abc", "isActive": true }, { "key":5, "value": "ade", "isActive":true } ] } I would like to be able to...

mongodb C# error on first Push

c#,mongodb,mongodb-csharp
I've a Parent Entity that has a property of list of Child Entities. Initially on Insert I don't have values for the child entities. But when I try to Update(by calling push) the document with Child Entities it fails. This works when I insert a dummy child entity value to...

How to update all document fields except specified ones in mongodb

c#,.net,mongodb,mongodb-csharp
I present a simple model: public class UserDocument { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } public string DisplayName { get; set; } public List<string> Friends { get; set; } } I am using the latest C# driver which has the ability to replace a document using a C#...

Adding serialization information for MongoDB custom serializer

c#,serialization,mongodb-csharp,querying
I have a class defined as follows: class Person { public String Id { get; set; } public String Name { get; set; } public Person Mother { get; set; } } I've implemented a custom serializer for the Mother property to serialize the Id only. The final BSON would...

Query with filter builder on nested array using MongoDB C# driver

c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0
Consider the following object structure stored as documents: public class Foo { public string Id { get; set; } public ICollection<FooBar> Bars { get; set; } // ... } public class FooBar { public string BarId { get; set; } // ... } Using a LINQ-style query with the driver...

c# mongodb driver groupby

c#,mongodb,mongodb-csharp
I try to execute this query: MongoCollection<AnalyticsClicks> dbCollection = DetermineCollectionName<AnalyticsClicks>(); var query = from c in dbCollection.AsQueryable() where c.UserId == userId && c.CampaignId == campaignId select new { c.Email, c.Link }; var res = query.GroupBy(x => x.Email, b => b.Link).Count(); but I have exception: The GroupBy query operator is not...

Server side projection with MongoDB C# driver 2.0

c#,.net,mongodb,mongodb-csharp,projection
I have a collection of documents with a few small properties, and one huge property (a binary 10MB or so PDF document). I'm using the latest stable C# driver, published on 2015-04-02. Is there a way to get a list of these documents, with all the small properties, but excluding...

Index hint with mongodb csharp driver 2.0.0

mongodb,mongodb-csharp
I am migrating from the mongodb csharp driver 1.10.0 to 2.0.0. One of the collection I am using is very big and has to fulfill many queries with different filter attributes. That is why I was relying on some index hint statements. With the v1.10 driver it looks like myCollection.Find(query).SetHint("myIndexName");...