user636525
user636525

Reputation: 3200

Schema design for inner documents to help in searching

I am looking for advice on how to proceed with a design issue with MongoDB. I have a User document with inner documents.

public class User
{
  public ObjectId Id {get;set;}
  public string UserName {get;set;}
  public List<Skills> SkillLists{get;set;} 
  public string xxxx {get;set;}
  public string yyyy  {get;set;}
  public string zzzzz {get;set;}
}

public class UserSkills
{
  public ObjectId Id {get;set;}
  public ObjectId UserId {get;set;} // contains reference to UserId
  public string UserName {get;set;}
  public List<string> Skills {get;set;} This is just an array of strings to help me search
}

I am keeping a separate collection to help me search for users with specific skills. My question is , since my app has the ability to let user change the username,do i need to update all the UserSkills records with the new username ?

Am i not designing the schema right ?

Upvotes: 0

Views: 59

Answers (2)

bauman.space
bauman.space

Reputation: 2023

By the looks of it, you are trying to shoehorn SQL like structure to MongoDB.

MongoDB/NoSQL standard model for one to many relationship is via embedding sub documents http://docs.mongodb.org/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/

How you create classes in your application is up to you, but the map to the storage layer probably wants a user to look like this:

You may want a document that looks like this:

{
   _id: "...",
   UserName: "Joe Bookreader",
   Skill: [
            {
              Name: "Microsoft Word",
              level: "Expert
            },
            {
              Name: "Linux",
              level: "Novice"
            },
          ],
   xxxx: "",
   yyyy: "",
   zzzz: ""
 }

then

db.users.find({"Skill.Name":"Microsoft Word"})

returns the entire document.

That way a change to the Username has no impact on the skill list

Upvotes: 1

woemler
woemler

Reputation: 7169

At a quick glance, it does not look like there is any need to embed the UserID and UserName fields in the UserSkills collection. Looking at this logically, a skill is not necessarily unique to an individual. Users can presumably have multiple skills, and multiple users can probably have the same skill, so making the UserID or UserName and attribute of the skill makes no sense.

You are probably better off having two collections, Users and Skills and nesting references to skills within the user documents. You can index a key within the Users.Skills subdocument to make searching easier.

Upvotes: 0

Related Questions