Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB best practice for referencing

Tags:

I'm wondering what the best practice for modelling by using references would be given situation under. I'm using MongoRepository library.

public class User : Entity {    publis string Id { get; set; }    public string Email { get; set; }    public string Password { get; set; } }  public class Post : Entity {    public string Id { get; set; }    public string Title { get; set; }    public string Summary { get; set; }    public DateTime Added { get; set; }    public User Owner { get; set; } } 

When storing the Post I want only reference to Owner (User) object instead of whole object underlying.

Currently I'm doing it like this, not knowing of better way...

var post = new Post {    Title = "Example title",    Summary = "asd asd",    Added = DateTime.Now,    Owner = new User { Id = "someExistingUserId" } }; postRepository.Update(post); //Save 

..

//Then to get the post var post = postRepository.GetById("previouslySavedPostId"); post.Owner = userRepository.GetById(post.Owner.Id); return post; 

userRepository and postRepository are of MongoRepository type.

Is this the correct approach to solving my problem using MongoDB with C#/MVC(4)?

like image 917
Xatep Avatar asked Feb 14 '13 14:02

Xatep


People also ask

How do I reference in MongoDB?

MongoDB applications use one of two methods to relate documents: Manual references save the _id field of one document in another document as a reference. Your application runs a second query to return the related data. These references are simple and sufficient for most use cases.

Does Sharding improve performance in MongoDB?

Sharded clusters in MongoDB are another way to potentially improve performance. Like replication, sharding is a way to distribute large data sets across multiple servers.

Is MongoDB good for relations?

One of the primary benefits of creating Embedded Relationships in MongoDB is that the queries are executed faster than the referenced relationship. This relationship also improves performance, and results are obtained quickly. This is also true for large datasets.


1 Answers

You can use MongoDBRef object instead of User object.

public class Post : Entity {     public string Id { get; set; }     public string Title { get; set; }     public string Summary { get; set; }     public DateTime Added { get; set; }     public MongoDBRef Owner { get; set; } }     

Then you can:

var mongo = new Mongo(config.BuildConfiguration()); mongo.Connect();         var DB = mongo.GetDatabase(_dataBaseName)  var post = new Post(); post.Owner = new MongoDBRef("User", userId); // First parameter is a mongoDB collection name and second is object id // To fetch object referenced by DBRef you should do following var owner = DB.FollowReference<User>(post.Owner); 
like image 75
Jasmin Gacic Avatar answered Sep 22 '22 14:09

Jasmin Gacic