Menu
  • HOME
  • TAGS

How to not insert a field in mongodb if it is null?

c#,asp.net,.net,mongodb,mongodb-csharp

Update: As requested by people in the comments, i am including a proper answer to the solution with the link as a reference. Below is the code snippet that sets the date field in a mongodb document if the nullbale 'mydate' parameter has a value, or simply does not create...

Index hint with mongodb csharp driver 2.0.0

mongodb,mongodb-csharp

You can use the FindOptions.Modifiers property. var modifiers = new BsonDocument("$hint", "myIndexName"); await myCollection.Find(query, new FindOptions { Modifiers = modifiers }).ToListAsync(); May I ask why you are using the hint? Was the server consistently choosing the wrong index? You shouldn't need to do this except in exceptional cases. Craig...

Delete subdocument from array

c#,mongodb,mongodb-csharp

For updating multiple documents you should set the update flags to Multi: MyMongoCollection.Update(query, update, UpdateFlags.Multi); This will remove subdocuments from all documents. From the MongoDB documentation: By default, the update() method updates a single document that matches its selection criteria. Call the method with the multi option set to true...

Use of MongoDB in a Windows Service

c#,.net,mongodb,database-connection,mongodb-csharp

The mongo driver does the connection pooling for you. There's no need to worry about it. You won't create a new connection on every save and you don't need more than a single MongoClient....

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

c#,mongodb,mongodb-csharp

The message almost explained itself. You defined the Symbol as a string, while in database there's some document that has a double type Symbol. It's causing a deserializing issue. To find out these illegal data, try: db.StockLookup.find({Symbol: {$type: 1}} DON'T do this if you have a big amount of data...

c# mongodb driver groupby

c#,mongodb,mongodb-csharp

I think the driver just doesn't implement the Linq GroupBy method. Use aggregate framework instead. You can find good examples here - MongoDB Aggregation Framework Examples in C# You don't need to link any new libraries the support for the aggregation framework goes with MongoDB C# driver. Hope it helps!...

Ignore a property when saving a POCO in MongoDB, but not ignoring it when serializing to JSON

c#,json,mongodb,mongodb-csharp,bson

I don't think that's possible while you're using the driver itself to serialize your objects into json. However you can (and probably should) use json.net to serialize into json. That way your BsonIgnore will have no effect on json serialization and the json attributes (like JsonIgnore) will have no effect...

Find document with highest calculated value in mongodb using c# driver

c#,.net,mongodb,mongodb-query,mongodb-csharp

Unfortunately, this can't be done using the LINQ syntax. It's easier (and more specific) to use the canonic aggregation syntax as it is documented in the official "Aggregation Pipeline" documentation. Example Input: { _id: 1, Grades: [ 1, 1 ] } { _id: 2, Grades: [ 2, 3, 4 ]...

How to handle multithreading MongoDb updates from .net classes?

mongodb,mongodb-csharp

From what I understand, you want optimistic locking. A straightforward way to implement optimistic locking is to version your documents and increase the version number with every update, i.e. public void Update(MyClass document) { db.GetCollection<MyClass>("MyClass").Update( Query.And( Query<MyClass>.EQ(p => p.Id, document.Id), Query<MyClass>(p => p.Version, document.Version), Update<MyClass>.Replace(document).Inc(p => p.Version)); } Now let's...

How to retrieve a property from an object within a dictionary in a MongoDB document?

c#,mongodb,mongodb-csharp

I defined the LogEntry class as public class LogEntry { public ObjectId Id { get; set; } public IDictionary<string, object> ExtendedProperties { get; set; } } then I inserted the sample document by var log = new LogEntry { ExtendedProperties = new Dictionary<string, object> { { "Context", new LoggingContext {...

MongoDB C# Driver 2.0 - Update document

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0

I think you're looking for ReplaceOneAsync(): MyType myObject; // passed in var filter = Builders<MyType>.Filter.Eq(s => s.Id, id); var result = await collection.ReplaceOneAsync(filter, myObject) ...

How to add object of type dictionary as BsonElement in BsonDocument

c#,mongodb,dictionary,mongodb-csharp

I just needed to add nested BsonDocument as an element to parent BsonDocument. That's it! public void batchInsert(Question Model) { _collection = _db.GetCollection<Question>("Question"); BsonDocument[] batch = new BsonDocument[Model.QuestionList.Count]; int count = 0; foreach (Question question in Model.QuestionList) { BsonDocument rulesBsonDoc = new BsonDocument(); foreach (KeyValuePair<string, VariableDetails> qTemp in question.Rules) {...

mongodb C# error on first Push

c#,mongodb,mongodb-csharp

To Hazard a guess, it's because the "array" field in the database is null after the insert. You either need to make the initial value in the database an empty array, or you need to make it not-present. You can either: use the [BsonIgnoreIfDefault] attribute on your list field to...

Mongo c# difference between implementing IBsonDocumentSerializer and registering BsonClassMap

mongodb,mongodb-csharp

Start with a BsonClassMap first. It will fit a vast majority of use cases: http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/mapping/. If you need more power, then implement IBsonDocumentSerializer, but that is relatively complex to get right for all the edge cases....

C# MongoDB Driver Concurrent Update Issue(with test code)

c#,mongodb,concurrency,mongodb-csharp,insert-update

That happens because DateTime.Now.Ticks is not very precise and will often return the same value. Have you looked at the data you're creating? Many time values are equal (depending on how fast your machine is). The collision can only happen in the middle where the two walking directions meet. The...

MongoDb c# bad unknown operator exception

c#,mongodb,mongodb-csharp

That isn't a valid query. While you can add $orderby that way (but it's not recommended), skip and limit are not part of the document. Best thing to do is to not try to build it that way and instead let the driver build it for you. This will also...

MongoDB 2 - query array without hardcoding name

c#,mongodb,mongodb-csharp

You are looking for the AnyEq method. See the docs here: http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/definitions/#array-operators var filter = Builders<Issue>.Filter.AnyEq(x => x.AssignedTo, id.ToString()); ...

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

c#,mongodb,mongodb-csharp

You can build simple queries using lambda expression, MongoDB.Driver supports it var collection = database.GetCollection<Item>("Item"); var list = await collection.Find(x => locationIds.Contains(x.LocationId)).ToListAsync(); ...

Searching an array of objects in MongoDB using the C# Driver

c#,mongodb,mongodb-csharp

The EQ method accepts only BSONValue as a parameter, but you're trying to pass a IMongoQuery instance. In your second query you're basically searching this document in MetaData array : {"FileExtension":"TXT"} You will need to create a new BsonDocument and pass it into your EQ method: Query.EQ("MetaData", new BsonDocument(leaf.Field, leaf.Value));...

cannot do asqueryable on mongodb collection

c#,.net,linq,mongodb,mongodb-csharp

You are missing a namespace, MongoDB.Driver.Linq, simply add that at the top: using MongoDB.Driver.Linq; That specific method is: LinqExtensionMethods { public static IQueryable<T> AsQueryable<T>(this MongoCollection<T> collection); //... } ...

Pass object to Query.EQ in MongoDb csharp driver

c#,.net,mongodb,mongodb-query,mongodb-csharp

Try this: public IMongoQuery Equals(string name, object value) { var val = BsonValue.Create(value); return Query.EQ(name, val); } ...

MongoDB internal data type for numbers

mongodb,mongodb-csharp,bson

I haven't encountered anything similar. Regarding your second question, I use MongoVUE and it has a Type column: ...

Unwind then Group aggregation in MongoDB C#

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0

When you let Unwind infer the type parameters it will use the collection type for TResult and BsonDocument for TNewResult. If you want to use a specific type and not BsonDocument you need to add these type parameters: var pipeline = usersCollection.Aggregate() .Unwind<OriginalType, NewResultType>(.... As always, you need to make...

Automatic merge of objects referenced from another collection

c#,.net,mongodb,mongodb-csharp

Assuming you already have a sitCollection: public Wsp GetFullWsp(Guid id) { var wsp = wspCollection.AsQueryable().FirstOrDefault(w => w.WspId == id); var sits = sitCollection.AsQueryable().Where(sit => sit.WspId == id); wsp.SitList = new List<Sit>(sits); } But, I think you may want to consider your model. I see 3 options: Have a single collection...

Slice with Projection with C#

mongodb,c#-4.0,mongodb-query,mongodb-csharp

There is a way to do this with the C# driver. Methods can be chanined on builders, so all of .Slice() and .Include()and .Exclude() var fields = Fields.Slice("empActivity", -1) .Include("employeeId", "empActivity.transId") .Exclude("_id"); var cursor = collection.Find(query).SetFields(fields); ...

Ensure utilization of compound index with lambda

c#,mongodb,lambda,mongodb-csharp

The order in which your query is built, whether by typing in json explicitly or generating it from a lambda expression has no effect on the index selection. When you have a compound index in MongoDB the order of the properties in the index matters but the order in the...

search by substring in mongodb from powershell

mongodb,powershell,mongodb-csharp,mongodb-query

Give this a try: $query = @{ 'field1' = $notification['A'] 'field2' = $notification['B'] 'field3' = @{ '$regex' = '.*' + $notification['C'] + '.*'; '$options' = 'i' } } $cursor = $collection.find([MongoDB.Driver.QueryDocument]$query) ...

Query with $in operator and large list of Ids

mongodb,mongodb-csharp

It's somewhat of an anti-pattern, but sometimes there's no other choice. If you can change the schema and make that query redundant then you should. If you can't, doing it yourself will surly be slower than letting MongoDB do it. However, there is another limit you need to consider. Each...

Unable to retrieve subdocument items in mongodb c#

c#,asp.net-mvc,mongodb,pagination,mongodb-csharp

I solved the exception of deserializing, with following small changes: In SubDocumentModel: Public class SubDocumentModel { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } . . . } And when I insert the subdocument, I am saving the Id as object id not as a string (previously I was...

mongodb 2.0 query by discriminator

c#,mongodb,mongodb-csharp

Relevant feature request here: https://jira.mongodb.org/browse/CSHARP-1194 For now, you can use an "is" filter. collection.Find(x => x is Employee).ToListAsync(); You'll still need to cast at the end into an Employee, but they will all be filtered according to the registered discriminator....

Get a BsonDocument at a specific offset

c#,mongodb,mongodb-csharp

Edit: I think this is a better solution (I didn't know about ElementAt, as I've never actually needed to do this): var document = bsonCollection.FindAll().ElementAtOrDefault(randNumber); You should be able to achieve this using skip on the cursor. Something like: var cursor = bsonCollection.FindAll(); cursor.Skip = randNumber; var document = cursor.FirstOrDefault();...

Does MongoDB successful insert guarantee populated ID's?

c#,.net,mongodb-csharp,mongodb-csharp-2.0

Yes. If the operation completed without errors you are guaranteed that the documents have an ID (either created by you before the operation or by the driver in the operation itself). Moreover, since the IDs are generated by the driver itself (client-side) before calling the MongoDB server there's a good...

Opening a MongoDB GridFS by name with C# Driver

c#,python,mongodb,pymongo,mongodb-csharp

A sample using grid in c#: var url = new MongoUrl("mongodb://localhost"); var Client = new MongoClient(url); var Server = Client.GetServer(); var Database = Server.GetDatabase("test"); var collection = Database.GetCollection("test"); var set = new MongoGridFSSettings {UpdateMD5 = true, ChunkSize = 512*1024, VerifyMD5 = false}; // you can set the name here set.Root...

MongoDB: Querying for a referenced document

c#,.net,mongodb,mongodb-csharp

The difference is that the MongoDB C# driver can't translate the first snippet into a MongoDB query, while it can the second one. When you call Where on an IQueryable it stores all the lambda expressions until you materialize the query be using foreach or ToList. At that stage the...

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

mongodb,mongodb-csharp

BsonDocument provides flexible way to represent JSON/BSON in C#. Creating BsonDocument is similar to creating JSON objects. Simple document new BsonDocument("name", "Joe") creates JSON { "name" : "Joe" } More complex document new BsonDocument { {"Name", "Joe"}, { "Books", new BsonArray(new[] { new BsonDocument("Name", "Book1"), new BsonDocument("Name", "Book2") }) }...

MongoDB. Index was out of range

c#,mongodb,mongodb-csharp

You mention in the comments that the underlying issue is an OutOfMemoryException. Answer here suggests paging best practices MongoDB - paging...

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

c#,mongodb,mongodb-csharp

... and create the database there is no such operation in mongodb, databases are created when you attempt to insert data into one What am I missing? You're not asking the driver to actually do anything. All operations are lazy. To have the driver connect and insert a document,...

Get documents for base class and inheriting classes in one query

c#,.net,mongodb,polymorphism,mongodb-csharp

You need to show the driver your class hierarchy. There are 2 options, the first using BsonKnownTypes and BsonDiscriminator attributes, the other using BsonClassMap. Attributes Decorate your base class with the specific derived classes you want to include (similar to what you would do in WCF). To tell the driver...

Bulk inserting to MongoDB on Replicaset

c#,.net,mongodb,bulkinsert,mongodb-csharp

Yes. You can insert in bulk: Bulk Inserts in MongoDB IEnumerable<WriteConcernResult> results = collection.InsertBatch(records) That will cut on most of the round trips to the DB which should speed things up....

Using GridFS with official C# driver in MonoDevelop

c#,mongodb,monodevelop,mongodb-csharp,freebsd

You have downloaded the 2.0 version of the driver. It currently does not have a GridFS API. You can track that feature here(https://jira.mongodb.org/browse/CSHARP-1191). In addition, MongoServer is gone in the 2.0 API. However, there is a wrapper for the legacy API available available if you pull the mongocsharpdriver nuget package....

Get a child element from document

c#,json,mongodb,mongodb-csharp

BsonElement accept a parameter as name for root-level of field name such as 'field1', and you cant pass a nested name (using dot notation naming such as 'field1.nested_field'). You have to define some classes for your sub documents public class MyDataClass { public ObjectId _id { get; set; } public...

Detect MongoDB status

c#,.net,mongodb,mongodb-csharp

If by "detect status" you want to see whether you can access the server then use Ping: new MongoClient("mongodb://localhost:27017").GetServer().Ping(); It throws an exception if the server cannot be reached....

WriteConcernException when closing Mongo GridFS file stream

c#,mongodb,mongodb-csharp,gridfs,gridfs-stream

well, I'm not sure if it's a bug in MongoDB driver or not, but I've found the problem. I opened the GridFS file with OpenRead() so I thought I'm well protected. apparently not. I had a bug that called Seek to a position higher than the file length. this caused...

Server side projection with MongoDB C# driver 2.0

c#,.net,mongodb,mongodb-csharp,projection

You would want to use IFindFluent.Find and then use IFindFluent.Projection and Builders.Projection.Exclude to exclude this property: var query = collection. Find(filter). Project(Builders<Document>.Projection.Exclude(doc => doc.HugeBlob)); var results = await query.ToListAsync(); ...

How to prevent BSON deserialization instantiating members in a class?

deserialization,mongodb-csharp,bson

To get round my issue I refactored the properties to instantiate what they needed on the object created by the BSON deserialization process.

Encoding issue with string stored in database

c#,unicode,encoding,mongodb-csharp

Short version Your data is lost and there is no general solution how to recover the original strings. Longer version What supposedly happened when the data was stored, the strings where encoded as ISO-8859-1 but stored as Unicode UTF8. Here's an example: string orig = "Lernkärtchen"; byte[] iso88891Bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(orig);...

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

c#,.net,mongodb,mongodb-csharp

You can achieve that by telling the driver to always serialize MyEnum as a string using a custom serializer: public class MyEnumSerializer : StructSerializerBase<MyEnum> { public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, MyEnum value) { BsonSerializer.Serialize(context.Writer, value.ToString()); } public override MyEnum Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { return (MyEnum)Enum.Parse(args.NominalType,...

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

asp.net-mvc,mongodb-csharp

It was a hosting issue that triggered the problem. My primary server/shard had issues, so, as expected, the secondary became the new primary and then everything failed. The quick fix was to postfix the connect string with "?slaveOk=true". That fixed reading. Writing still failed. So the real issue here was...

MongoDB C# Driver - how to store _id as ObjectId but map to string Id property?

c#,mongodb,mongodb-csharp

This has changed, I'm using the latest 1.x driver (Nuget package <package id="mongocsharpdriver" version="2.0.0" targetFramework="net45" />) and instead of using SetRepresentation you set the serialiser. public class RegistrationAttempt { public string AttemptId { get; set; } } BsonClassMap.RegisterClassMap<RegistrationAttempt>(cm => { cm.AutoMap(); cm.MapIdProperty(c => c.AttemptId) .SetIdGenerator(StringObjectIdGenerator.Instance) .SetSerializer(new StringSerializer(BsonType.ObjectId)); }); ...

How long does mongodb wait for new data when opening a tailable cursor

mongodb,mongodb-csharp

No, it is not configurable. The wait time is anywhere between 2 and 2.3 seconds. You are not the only one who finds it to be a peculiar design decision....

mongodb c# select specific field

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0

You can do next: public async Task<TValue> GetFieldValue<TEntity, TValue>(string id, Expression<Func<TEntity, TValue>> fieldExpression) where TEntity : IEntity { var propertyValue = await collection .Find(d => d.Id == id) .Project(new ProjectionDefinitionBuilder<TEntity>().Expression(fieldExpression)) .FirstOrDefaultAsync(); return propertyValue; } and call it var value = await GetFieldValue<Item, string>("111", x => x.Name); ...

How to issue a find command using MongoDB C# Driver with native JSON criteria syntax? [duplicate]

c#,json,mongodb,mongodb-query,mongodb-csharp

Yes there is: var json = "{'_id': 3456}"; var doc= BsonDocument.Parse(json); var query = new QueryDocument(doc); var result = coll.Find(query); ...

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

c#,mongodb,serialization,mongodb-csharp

Also asked here: https://groups.google.com/forum/#!topic/mongodb-user/iOeEXbUYbo4 I think your better bet in this situation is to use a custom discriminator convention. You can see an example of this here: https://github.com/mongodb/mongo-csharp-driver/blob/v1.x/MongoDB.DriverUnitTests/Samples/MagicDiscriminatorTests.cs. While this example is based on whether a field exists in the document, you could easily base it on what type the...

Add item to nested array of nested object using MongoDB C# Driver

c#,.net,mongodb,mongodb-csharp

There is no typed version query for do such a thing, you have to use string based query var query = Query.And(Query.EQ("id", "Org1"), Query.EQ("Divisions.id", "Div1")); collection.Update(query, Update.AddToSet("Divisions.$.UsersInDivision", "User3")); The reason you cant use strongly typed version is $ operator. There is no $ in current version of mongodb c# driver....

Custom name/type of document ID and performance

c#,mongodb,mongodb-csharp

First question, just add BsonId like: [BsonId] public ObjectId ObjId {get; set;} // not called Id Which indicates that this filed is primary key and should be mapped to _id field. Basically you can use anything as ID, there's no limitation you must use some specified type. Thus you can...

How to cast mongo collection to interface C#

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0

There are 2 questions here. How do you cast Task<List<Foo>> to Task<IList<IFoo>>? You can't, because Task isn't covariant in .Net. You can unwrap the result with await but it still wouldn't work as you can't cast List<Foo> into IList<IFoo>. What you can do is create a new List<IFoo> and cast...

How do you manage connections to mongodb from C#?

c#,mongodb,mongodb-csharp

MongoClient is added to the driver since 1.7, to manage replica set stuff. It's supposed to be singleton and is thread-safe. You can always get MongoServer from it. You don't need to worry about closing connections. It's managed by the driver. Refer to the tutorial for more information.

BsonClassMapSerializer already registered for AbstractClassSerializer

mongodb-csharp

My assumption must have been correct because I just fixed this by doing the BsonSerializer registration before creating the MongoClient and getting the database. Hopefully this will help someone else.

Is combining MongoDB with Neo4J a good practice? [closed]

mongodb,neo4j,nosql,mongodb-csharp,neo4jclient

Personnally I think there are no unique answer and best practices. It is common usage to use polyglot persistence systems. Now everything is based on your context and there are points we can't just reply for you : How much time do you have (learning a new technology is not...

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

c#,mongodb,mongodb-csharp,mongodb-csharp-2.0

It's helpful to understand the basics of async / await because it's a somewhat leaky abstraction and has a number of pitfalls. Essentially, you have two options: Remain synchronous. In this case, it's safe to use .Result and .Wait() on the async calls, respectively, e.g. something like // Insert: collection.InsertOneAsync(user).Wait();...

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

mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0

The logic is flipped, what you need is an $in query if I understand your use case correctly: var filter = Builders<Post>.Filter.In("username", usernameList); var result = collection.Find(filter).ToListAsync().Result; In your case, username is a simple field and you want to match against a list of candidates. AnyEq is used to check...

MongoDB .Net driver 2.0 Pull (remove element)

c#,mongodb,mongodb-csharp

When using a filter to remove array elements, you need to use the PullFilter builder instead of Pull (which matches whole elements). var filter = new BsonDocument("username", "bodrum"); var update = Builders<Person>.Update.PullFilter("followerList", Builders<Follower>.Filter.Eq("follower", "fethiye")); var result = collection.FindOneAndUpdateAsync(filter, update).Result; Or somewhat more succinctly, using lambdas: var update = Builders<Person>.Update.PullFilter(p =>...

How to update all document fields except specified ones in mongodb

c#,.net,mongodb,mongodb-csharp

There is no way, using the provided builders to have a "blacklist" update which excludes only specific fields. You can query the old document, copy the old values of these fields to the new instance and then replace it entirely in the database. You can also generate such an update...

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

c#,linq,mongodb,mongodb-query,mongodb-csharp

I am not aware of away to create the class out of mongodb just as we have with EF and linq-to-sql. I suggest you do one of two things, and i believe the second solution will harder but closer to what you asking 1) Try use bsonextractelements attribute to catch...

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

c#,mongodb,mongodb-csharp

See most recent update. A combination of the positional and $currentDate operators is serving my purpose.

Initialize MongoClient with MongoClientSettings in C#

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0

I could reproduce the problem, only in my error message, there is some much more helpful information buried somewhere in about 40 lines of text: No such host is known It turns out that MongoServerAddress only expects the hostname, not the protocol: settings.Server = new MongoServerAddress("localhost"); ...

get all documents from mongoDB collection

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0

Using the current version of the driver (v2.0) you can do that by passing a filter that matches everything: var documents = await SpeCollection.Find(_ => true).ToListAsync(); They have also added an empty filter (FilterDefinition.Empty) which will arrive in the next version of the driver (v2.1): var documents = await SpeCollection.Find(Builders<Project>.Filter.Empty).ToListAsync();...

Run Through a MongoDB collection in reverse mode

c#,.net,mongodb,mongodb-csharp

Just create an index on your date field like this: db.collection_Save.createIndex({date: -1}) then you can query your collection in this way: db.collection_Save.find().sort({date: -1}).skip(last_n).limit(1) where last_n is the number (counted from the end) of the document you want to get....

Multiple composite keys

mongodb,mongodb-csharp

From the C# side, you can use the IndexKeys.Combine helper to create such an index: await coll.Indexes.CreateOneAsync(Builders<MyEntity>.IndexKeys.Combine( Builders<MyEntity>.IndexKeys.Ascending("list.a"), Builders<MyEntity>.IndexKeys.Ascending("list.b")), new CreateIndexOptions() { Unique = true, Sparse = true }); One odd behavior is that the constraints are not enforced within a single document (SERVER-1068) because indexes are not considered 'within'...

Best way to create a text index on a MongoDB collection via C# driver

mongodb,mongodb-csharp

This should work: collection.EnsureIndex(IndexKeys.Text("a", "b").Ascending("c"), IndexOptions.SetTextLanguageOverride("idioma").SetName("custom").SetTextDefaultLanguage("spanish")); https://jira.mongodb.org/browse/CSHARP-874 https://github.com/mongodb/mongo-csharp-driver/commit/1e7db3bedb3bee1b0ccecdb5f8ff39854526213a...

With mongodb and c# driver, how to deserialize json to anonymous type?

c#,mongodb-csharp

Seems current version of the driver cannot deserialize anonymous types.

Update all properties of object in MongoDb

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0

You can do that with ReplaceOneAsync instead of UpdateOneAsync. You need a filter to match the existing document (a filter with the document id is the simplest) and the new object. Hamster hamster = ... var replaceOneResult = await collection.ReplaceOneAsync( doc => doc.Id == hamster.Id, hamster); ...

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

c#,mongodb,mongodb-csharp

FindOneAndUpdateOptions has ReturnDocument enum where ReturnDocument.Before = 'new':false ReturnDocument.After = 'new':true In your case options should be: var options = new FindOneAndUpdateOptions<ObjectSequence, ObjectSequence>() { ReturnDocument = ReturnDocument.After, IsUpsert = true }; ...

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

c#,linq,mongodb,mongodb-csharp,mongodb-csharp-2.0

MongoDB.Driver 2.0 doesn't support Linq.All. Anyway you task can be resolve next way: var filterDefinitions = new List<FilterDefinition<DocumentEntity>>(); foreach (var criteria in searchCriterias) { filterDefinitions .AddRange(criteria.Values .Select(value => new ExpressionFilterDefinition<DocumentEntity>(doc => doc.Criterias .Any(x => x.Category == criteria.Category && x.Values.Contains(value))))); } var filter = Builders<DocumentEntity>.Filter.And(filterDefinitions); return await...

C# mongoDB driver database connection

c#,asp.net,mongodb,mongodb-csharp

You have to change the Prijs to a number Run this in mongo console: db.moederborden.find().forEach(function(doc) { var price = doc.Prijs.replace(',', ''); // it may be vary for your other document price = price.replace('-', ''); doc.Prijs = Number(price); db.moederborden.update({_id : doc._id} , doc); }) ...

Get generated script in MongoDB C# driver

c#,.net,mongodb,mongodb-csharp,mongodb-csharp-2.0

You can use the integrated mongodb profiler to see what the database has actually received: db.setProfilingLevel(2); // log every request // show the requests that mongodb has received, along with execution stats: db.system.profile.find().pretty() Alternatively, you can step in the source code of the driver and wait for it to actually...

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

c#,arrays,mongodb,subset,mongodb-csharp

Use mongo Set Operator using $setIsSubset in aggregation you will get your result, check following query : db.collectionName.aggregate({ "$project": { "Name": 1, "Tags": 1, "match": { "$setIsSubset": ["$Tags", ["A", "B", "C"]] //check Tags is subset of given array in your case array is ["A","B","C"] } } }, { "$match": {...

MongoDB Unable to determine the serialization information for the expression error

c#,.net,mongodb,mongodb-csharp

As the error suggests, you can't use Int32.Parse inside your query. This lambda expression is used to get out the name of the property and it doesn't understand what Int32.Parse is. If you are querying a string, you need to use a string value for comparison: var parameterQuery = Query.And(Query<Parameter>.EQ(p...

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

mongodb,asp.net-web-api,odata,mongodb-csharp,asp.net-web-api-odata

Comment moved to answer: You aren't returning an IQueryable from GetAllStoreCommands(). Your return type must be an IQueryable(). To get that from the driver, it should be _collection.AsQueryable()....

Filtering mongodb data

c#,.net,mongodb,mongodb-csharp

According to your sample I used id = "54c00c65c215161c7ce2a77c" and prgDate = "2212015" then I changed the query to this: var collection = database.GetCollection<Channel>("test6"); var id = new ObjectId("54c00c65c215161c7ce2a77c"); var query = Query.And(Query<Channel>.EQ(c => c.Id, id), Query<Channel>.EQ(c => c.DailyPrograming.Name, "2212015")); var result = collection.Find(query).FirstOrDefault(); this query works fine Some point:...

C# : Retrieve array values from bson document

c#,mongodb,mongodb-csharp

If I got your problem correctly, One approach is : var queryString = Query.EQ("_id", id); var resultBsons = collection.FindOne(queryString); var arrayOfStrings = resultBsons["loves"].AsBsonArray.Select(p => p.AsString).ToArray(); ...

MongoDB Serialisation/Deserialisation of objects

c#,mongodb,serialization,mongodb-csharp,bson

The problem is that GenericIdentity is not a data class and has a lot of properties that you don't want persisted. In this case, you're going to want to map this manually. Below, I'm going to map the only two properties that actually matter, the Name and the AuthenticationType. I'm...

How to create ids for subdocuments in Mongodb with c#

c#,mongodb,mongodb-csharp

This way uses custom object serialzer for mongo: 1- write the serializer: public class TestSerialzer : IBsonSerializer { public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { return BsonSerializer.Deserialize<Test>(bsonReader); } public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { throw new NotImplementedException(); } public IBsonSerializationOptions GetDefaultSerializationOptions() { throw...

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

c#,mongodb,mongodb-csharp

The following query should work var oId = new ObjectId(lastStatistic, 1, 1, 1); var query = Query<UserRecord>.GTE(e => e.Statistics, oId); you can create an ObjectId based on the lastStatistic Date which is your cut-off. Then you can just query the UserRecord collection to find any records that have an item...

Update complex types without wrapping

c#,mongodb,mongodb-csharp

When using Generics instead of objects, the conversion to BsonValue is not necessary.

MongoDB retrieve only matching sub documents from a document with c#

mongodb,c#-4.0,mongodb-query,mongodb-csharp

The desired output could be produce just by aggregation: db.collection.aggregate([ {$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate("2015-01-09T12:33:39.927Z")} }}, {$unwind : '$empActivity'}, {$match : { empId : '999', 'empActivity.Stamp' : { $lte : ISODate("2015-01-09T12:33:39.927Z")} }}, {$group: { _id: '$empId', empActivity: { $addToSet: '$empActivity' }}} ]) in...

New (2.6) $cond Aggregation Framework with c#?

mongodb-csharp

Give this a try: var group = new BsonDocument { { "$group", new BsonDocument { { "_id", "$Code" }, { "Special", new BsonDocument { { "$sum", new BsonDocument { {"$cond", new BsonArray { new BsonDocument { { "$eq", new BsonArray {"$Special", "Success"} } }, 1, 0 } } } }...

How to cancel MoveNext operation on tailable cursor

c#,.net,mongodb,mongodb-csharp

If you don't set a timeout on the cursor then that's pretty much all you can do, as long as the MoveNext method doesn't accept a CancellationToken. Just dispose of the enumerator, catch the ObjectDisposedException and move on. I have a solution example for a similar case here. Which in...

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

mongodb,mongodb-csharp,mongodb-csharp-2.0

OK, I figured out how to correct this date issue. The date time string that I got from JSON.Net, was not getting stored a BSON date object. So I had to call the BsonDateTime.create() method on the deserialized BsonDocument property and force it to be a BSON date. When it...

Query deeply embeded documents in MongoDB with C# driver

c#,mongodb,mongodb-csharp

You can use $elemMatch to match nested element in array. I used headingTitle to match here. Query will be like following- db.collection.find({ "bookChapters": { "$elemMatch": { "chapterArticles": { "$elemMatch": { "articleHeadings": { "$elemMatch": { "headingTitle": "headingTitle" } } } } } } }) If you want to convert it to...

MongoDB C# Nullable Datetime Query

c#,.net,mongodb,datetime,mongodb-csharp

You can compare the DateTime? to null instead of using HasValue: Collection.AsQueryable<Candidate>( c => c.IndexMetadata.Indexed == null || c.IndexMetadata.Updated.Value > c.IndexMetadata.Indexed.Value). ToList(); ...

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

c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0

The query you need to perform uses the $elemMatch query operator. So, this query using a lambda expression var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123")); Is equivalent to this query using the FilterDefinitionBuilder: var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch( foo => foo.Bars, foobar => foobar.BarId == "123")); ...

How to run the mongodb $where operator in powershell

mongodb,powershell,mongodb-csharp

SOLUTION: $tagCollection = $db["tag"] $query = @{ '$where' = "'star wars episode VII'.search(this['name']) >= 0;" } $cursor = $tagCollection.find([MongoDB.Driver.QueryDocument]$query) ...

Adding serialization information for MongoDB custom serializer

c#,serialization,mongodb-csharp,querying

Yes, there are two interfaces you may implement to provide serialization information. IBsonDocumentSerializer and IBsonArraySerializer. In this case, you'll want to implement IBsonDocumentSerializer on your customer serializer and handle the GetMemberSerializationInfo call for the memberName Id.

Inserting object into embedded document

c#,mongodb,mongodb-csharp

Try this: var query = Query<PlayList>.EQ(e => e.Id, playListId); var update = Update<PlayList>.Push(e => e.UrlList, url); collection.Update(query, update); ...