robthree / mongorepository Goto Github PK
View Code? Open in Web Editor NEWRepository abstraction layer on top of Official MongoDB C# driver
Home Page: https://www.nuget.org/packages/MongoRepository/
License: MIT License
Repository abstraction layer on top of Official MongoDB C# driver
Home Page: https://www.nuget.org/packages/MongoRepository/
License: MIT License
Working on a customers project. Cant update MongoDB to 2.4 cause MongoRepository requires 1.1!
Best regards
This is half question, half bug report.
I believe there might be a significant bug in MongoRepository's management of the lifecycle of MongoServer. I believe MongoServer should be singleton/static, and the same instance should be used every time. Otherwise there's some overhead in connecting to the database with each instantiation of the repository.
Here in Util.cs:
private static MongoDatabase GetDatabaseFromUrl(MongoUrl url)
{
var client = new MongoClient(url);
var server = client.GetServer(); // <---- should not be returning a new MongoServer instance!
return server.GetDatabase(url.DatabaseName); // WriteConcern defaulted to Acknowledged
}
I picked this up when looking at performance of queries - was seeing 200ms+ overhead with each new MongoRepository.
Apologies if I have misunderstood the code.
Are there any plans to switch to the latest stable MongoDB driver aka 2.3.0? That would be great since I was using the latest version before installing this package and now it replaced the installed versio and some of my code broke.
Hi team,
How can I register the MongoRepository class in Castle Windsor?
The sample class I add earlier was
public class Author:Entity
{
public virtual string name { get; set; }
public string dob { get; set; }
}
and the response on getting list of authors was
[
{
"id": "5a2983589157cf906c39e808"
},
{
"id": "5a29899fcef3e85b9c427dd9"
},
{
"id": "5a29920fc9ea2c7a38f45085"
}
]
After adding DataMember to each property like below
public class Author:Entity
{
[DataMember]
public virtual string name { get; set; }
[DataMember]
public string dob { get; set; }
}
I was able to get the name and dob as part of the response
[
{
"name": null,
"id": "5a2983589157cf906c39e808"
},
{
"name": "Alayo Bolt",
"id": "5a29899fcef3e85b9c427dd9"
},
{
"name": "Alayo Bolt",
"id": "5a29920fc9ea2c7a38f45085"
}
]
Must I add the attribute [DataMember] to every field of my POCO classes before it could map to a field in the container document?
When returning collection of Product that inherits from Entity (using web api, JSON), only Id is returned. Am I missing something?
Would be possible to separate the Mongo-independent interface declarations (IRepository, IEntity) into an own assembly (something like Repository.Core) ?
This would allow to use the MongoRepository in client-server scenarios, where the clients would reference just the interface assembly, without having to be aware of the "real" database implementation (Mongo in this case).
Hello, I have defined this baseclass for my objects. I copied it from the Entity class because extending it would mess the collection name mapping mechanism.
[DataContract]
[Serializable]
[BsonIgnoreExtraElements(Inherited = true)]
public abstract class BaseObject : IEntity<string>
{
/// <summary>
/// Gets or sets the id for this object (the primary record for an entity).
/// </summary>
/// <value>The id for this object (the primary record for an entity).</value>
[DataMember]
[BsonRepresentation(BsonType.ObjectId)]
public virtual string Id { get; set; }
/// <summary>
/// This method could be invoked to set up somestuff
/// </summary>
public virtual void Init() { }
public virtual DateTime CreationDate
{
get {
if (!string.IsNullOrWhiteSpace(Id))
return ObjectId.Parse(Id).CreationTime;
return DateTime.MinValue;
}
}
}
}
The problem is that when I call the repository.Delete method nothing happens. I tracked down the code and got to the definition of the method. The problem is in that If statement that only limit the execution to the entity class items while it should be more about who implements the IEntity interface I think.
/// <summary>
/// Deletes an entity from the repository by its id.
/// </summary>
/// <param name="id">The entity's id.</param>
public virtual void Delete(TKey id)
{
if (typeof(T).IsSubclassOf(typeof(Entity)))
{
this.collection.Remove(Query.EQ("_id", new ObjectId(id as string)));
}
else
{
this.collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
}
}
A working solution would be to change it to
public virtual void Delete(TKey id)
{
if (typeof(T).GetInterfaces().Contains(typeof(IEntity<string>)))
{
this.collection.Remove(Query.EQ("_id", new ObjectId(id as string)));
}
else
{
this.collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
}
}
Best regards
Marco
So I'm just trying this out for the first time and I noticed that types like Guid and DateTimeOffset were getting serialized as binary blobs and/or byte arrays. Is that normal? I would have thought they would have called ToString() before storing or something.
I would like to see MongoRepository updated to use the latest 1.10.x version of the Mongo C# Driver and published to NuGet.
I'm using a MongoDB instance behind self-signed SSL, which means that to use this project I need to include sslVerifyCertificate=false on my connection string... that's bad. ๐ข
Do you think it would be a good idea to be able to initialise a MongoRepository by passing it a MongoClient. e.g.
var settings = new MongoClientSettings{ /*...*/ }
var client = new MongoClient(settings);
var db = client.GetServer().GetDatabase("mydb");
var repository = new MongoRepository(db, "mycollection");
Also it could be good to have a factory or context that provides the repositories -
var context = new MongoContext(db);
var repository = context.Repository<MyType>("mycollection");
This way you could pass an initialised context around and easily create repositories.
Just wondering when the v2 branch will release on NuGet ?
Hi,
I'm working on the update method where i want to update a document basing on the commentID. So, i created a Unique Index on that as below
postcomment.Collection.CreateIndex(new MongoDB.Driver.Builders.IndexKeysBuilder().Ascending("CommentID"), IndexOptions.SetUnique(true));
However when i use update statement for a document it throwing error as below
ERROR WriteConcern detected an error ''. (Response was { "ok" : 1, "code" : 11000, "err" : "E11000 duplicate key error index: SMAnalytics.FacebookComments.$CommentID_1 dup key: { : \"404484049735321_404495519734174\" }", "n" : NumberLong(0) }).
The below is the syntax which i'm using to upate
var cmt = new MComments() { PostID = "56772226", Comment = "Testing", FacebookID = "404484049735321", CommentID = "404484049735321_404495519734174", From = "Bhanu", Comment_Date = Convert.ToDateTime(comment.created_time), Like_Count ="10"}; postcomment.Update(cmt);
Please suggest some solution.. I should update the document If i already have that commentID..
I updated my MongoDB.Driver to 2.2.3 from a very old version 1.x.x and observed that so many things are broken. Like i cannot see IEntity inteface, ValidateCollectionResult, CollectionStatsResult, GetIndexesResult classes etc.
Build failed when building with .NET Platform 5.4 (ASP.NET Core)
Please correct Nuget definition for 1.3.0 version
Current dependencies:
mongocsharpdriver (>= 1.4.1)
Expected dependencies:
mongocsharpdriver (= 1.4.1)
Hi, I'm unable to write where condition on dates. Whenever I compare the dates it was just hanging. Here is the example
var data = postrepo.Where(x => x.CreatedDate== DateTime.Now);
We are using MongoRepositary in our project for CRUD operation , Mongo Repository using mongocsharpdriver package. Currently MongoRepository using mongocsharpdriver 1.1.0 version , but latest version of mongocsharpdriver is also available . How I can use MongoRepo with latest MongoDriver or mongocsharpdriver ?
Hello! I have been using MongoRepository for my project and I am keen to understand how best I incorporate the $lookup and $match aggregation features of Mongo 3.2?
I am trying to do this:
private readonly IRepository<UserItem> _userItemRepository; var pipeline = _userItemRepository.Aggregate() .Match(x => x.UserId == userId && x.PublisherId == publisherId);
but unfortunately it does not work (Intellisense errors all over the place) unless I bypass the MongoRepository and go to the MongoClient direct as so:
var client = new MongoClient("mongodb://localhost:27017"); var database = client.GetDatabase("MyDb"); var users = database.GetCollection<UserItem>("users"); var pipeline = users.Aggregate() .Match(x => x.UserId == userId && x.PublisherId == publisherId);
Looking for your advice on how best to approach this?
How to write near queries using this repository. I need one example that illustrates how to get the near all locations based on latitude and longitude.
and also how to achieve pagination using this repository.
Please help me as soon as possbile
2 example documents of users:
{
"_id": ObjectId("abc"),
"name": "Miroslav",
"tenants": [
"jin"
]
}
{
"_id": ObjectId("abd"),
"name": "Lothar",
"tenants": [
"zhu"
]
}
And I want to fire a single query to Mongo and get the matching documents . like sql server select * from users where id in('abc','abd')
how MongoRepository to do. thank you.
Unable to determine the serialization information for the expression: Enumerable.Select<News, String>(m.MsgBody.news, (News s) => s.title).
I user mongocsharpdriver 1.10.1 .mongodb 3.0 server.
my search code is
var msgList2 = messageRepository.Where(m => m.MsgBody.news.Select(s => s.title).Contains(keyword)).ToList();
data model is
What is the problem? Thanks.
Hey bud, I've been using MongoRepository for a long time and I LOVE it! It simplifies coding for MongoDB in .NET significantly.
However, there is a fundamental problem with it that greatly hinders scalability. See, the only way you handle updates is by updating the entire document in the database instead of only the properties that have changed. This is extremely wasteful because it uses more bandwidth than necessary to push an entire object, but it also forces the database to re-index the entire collection because the object has been replaced instead of updated.
Do you think this is something you can implement in MongoRepository? I would really appreciate it if you could. Maybe you can have something that tracks changes made to the models, and when "Update()" is called, it will only update the changed properties instead of replacing the entire object.
When returning an entity object (derived from Entity) from a Web method, only the Id property is retuned; all other properties of the object are ignored in Json format (xml is ok)
I use ASP.Net Web Api Controller Class v2.1
a work araound is to set the [DataMemberAttribute] to each property to export in Json
what about new version of driver?
i've installed the latest version but there is no aversion between two packages
It would be useful to expose MongoDB's count({ applySkipLimit: true }) and/or size() functions. These functions take skip() and limit() in consideration, so the queries will perform better.
This current package is incompatible with mongocsharp driver -v 2.4
i have collection like this.
{
"_id": ObjectId("554e05dfc90d3d4dfcaa2aea"),
"username": "bodrum",
"followerList": [
{
"_id": ObjectId("554e0625a51586362c33c6df"),
"follower": "fethiye",
"avatar": "fethiye.png"
},
{
"_id": ObjectId("554e0625a51586362c33c6df"),
"follower": "izmir",
"avatar": "izmir.png"
}
]
}
I want to remove first follower named as fethiye by follower field.
Hi Guys,
I would like to have my application abstracted from data store layer. But in order to use Generic Repository I have to inherit my entities from Entity class. I would like to have no references to your library from my application but inject data layer using container. Do you have any plans to support entities based on DataAnnotation attributes for example, or something else?
I am just curious if there are any plans to upgrade this project to support .NET Core and the latest MongoDB C# Driver?
I noticed that @cphillips83 had created a new project based on this one at https://github.com/MindMatrix/MongoRepository2.
I wondered if you all are planning to continue this project or are sunsetting it.
In version 1.6.8 the Delete function doesn't remove the item. I have to use Collection.Remove(query) for now as a work around.
Not an issue, but more of a feature request.
It would be nice to have an attribute to specify a different database name/ connection string. Currently, the entities will only use the connection string of "MongoServerSettings" If I have 2 collections in different databases, I'm not able to specify this to MongoRepository.
I would like to do something like this:
App.config
<connectionStrings> <add name="MongoServerSettings" connectionString="mongodb://localhost/Application?safe=true" /> <add name="UserDatabase" connectionString="mongodb://localhost/Users?safe=true" /> </connectionStrings>
Then in the Entity file, specify the secondary connectionstring like:
[ConnectionString("UserDatabase")]
public class User : Entity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
The entity file would by default use "MongoServerSettings" connection string unless the ConnectionString attribute was used.
Hi, I'm wondering how to be able to join two or more Repositories result by common properties (normally foreign pks) using this wonderful library. As fas as I know it could be done with EF and SQL but I am very happy with NoSQL.
As MongoRepository seems to implement IQueryable, do you think that something like the next code could work? (if in a fluent way were possible even better^^) thanks!
"from w in repo.Query()
join e in repo.Query() on.."
As everyone saying EnsureIndex is obsolete. Can you let me know how can I create an index for a collection? And can i do that at Entity level?
If I want to store document references instead of embedded documents, how would I best achieve that in the repo? For example, I want to have users that can share newspapers..so something like this, where people can keep references to their favorite newspapers.
class Newspaper:Entity { string Name; string Content; Data publishDate}
class User:Entity { string LastName; List<Newspaper>newspapers; }
But internally that List should be serialized to store references to newspapers inside user, not content.
How seamlessly can that be accomplished and should I manually be maintaining those references through in my derived repositories?
Should those references be through ObjectIDs or strings?
Thanks for any help.
Al
Hi,
I have created a model that inherits from Entity. And one that does not inherit from Entity.
The model that inherits from Entity instantiate the object but does not fill the property in the post request. See screenshots.
My model is like this:
public class EmailTransac : Entity
{ [Required()]
public string Name { get; set; }
[Required()]
public string From { get; set; }
[Required()]
public string Template { get; set; }
[Required()]
public string Subject { get; set; }
}
public class EmailTransacModel
{
[Required()]
public string Name { get; set; }
[Required()]
public string From { get; set; }
[Required()]
public string Template { get; set; }
[Required()]
public string Subject { get; set; }
}
With inherit of Entity
Without inherit of Entity
My Postman config
Any ideas how can I fix this?
Thanks,
Hi Everyone,
I can't run auth connection string. I can connect with any mongodb Gui editor or mongo.exe but Mongorepository always gives error "Command 'authenticate' failed: auth failed (response: { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 })". My connection string format is "mongodb://user:pass@localhost/DbName",
What is the problem? Thanks.
Hello,
How best i use MongoRepository in order to update an element within an Array within a Document? e.g., trying to emulate this code
http://stackoverflow.com/questions/31453681/mongo-update-array-element-net-driver-2-0
but the repo doesn't accept this:
var result = this._userRepository.Update(filter, update);
Any advice appreciated. thank you,
var newCustomer = new Customer {
FirstName = "Steve",
LastName = "Cornell"
};
// searching
var result = repo.Where(c => c.FirstName == "Steve");
// updating
newCustomer.LastName = "Castle";
repo.Update(newCustomer);
in the code above. Update method update one filed lastName or update all fields.
i want to update one field lastname.
Hi,
I want to ask, how do I force the MongoRepository to save enums to the mongodb as strings, instead of numbers?
Hi,
I would like to exetend the standard MongoRepository class.
I try to inherit from MongoRepository<t>
.
public class CustomMongoRepository<T> : MongoRepository<T>{}
but it does not work.
Is it possible to do it?
I would like to add some standard methods such as AddOrUpdate(string key) ...
Thanks,
The underlying driver is now at a 2.0 release which uses a fully async stack.
We'll have to update the repository for this release.
https://github.com/mongodb/mongo-csharp-driver/releases
I have a collection of documents who have a group of simple primitive fields (id, name, status) but also have a very large array on each. As an optimization to reduce query time I would like to only return the light weight document fields when querying the collection, similar to how a "select col1,col2,col3 from tbl" would work in SQL vs the "select * from tbl" I feel that mongo/mongorepository is doing.
Example:
Assume document model { id: 'string', name: 'string', bigarray: [{lots:'data'}]}
For a specific query, I only want to return models with id and name property to save bandwidth and query time by not returning the large payload of the bigarray property. I tried the following, but it feels like it's returning the entire document prior to creating the sparse model.
Repository.SearchFor(c=>c.id=="1234").Select(d=>new model(){ id=d.id, name=d.name}).ToList();
Here's my IRepository SearchFor implementation:
public IQueryable SearchFor(System.Linq.Expressions.Expression<Func<Model, bool>> predicate)
{
return Repository.Where(predicate);
}
Is it possible to return only specific fields from collection documents to create sparse models? I know about BSONIgnore, but that doesn't suit my needs, I need the bigarray property persisted since other queries need to return the full document and rely on that field.
As a longer term fix I'm in the process of refactoring the schema to move the "bigarray" property into it's own collection, and link with a relationship id, but I'm looking for a fix for the interim.
Thanks!
https://github.com/MindMatrix/MongoRepository2
Putting this here in case someone may find it useful, the code was taken from sidecut's https://github.com/sidecut/MongoRepository/tree/v2.4.2 as the base rather than here since it seemed to be the most complete.
I am new to MongoDB and am trying to get a grip on best practice..
In that past I would have created a Repository, a DataContext maybe a UnitofWork. At first when I looked at your code I thought the DataContext /UnitOfWork abstraction was missing, but thinking about it, the UnitOfWork can be encapsulated by instantiating a repository and performing some action on it. My question would be around latency in creating a connection to MongoDB every time you create a repository. Is there a heavy burden? Do you have any opinion around UnitOfWork etc?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.