Mongodb search and load one to many relationship

27 Views Asked by At

I am trying to search the contacts that has one to many relation with fields table. The search filters can be applied on "contacts" documents as well as on "fields". I am new to MongoDB from MySql background and will appreciate some help with this. Following is the DB design.

Fields Collection

[{
    _id:1,
    slug:field_one,
    name: Field One
},
{
    _id:2,
    slug:field_two,
    name: Field Two
},...]

Contacts Collection

[{
    _id:1,
    firstName:John,
    lastname:Doe,
    fields:[{
        value: abc,
        field_id: 1
    },{
        value: xyz,
        field_id: 2
    }]
},{
    _id:2,
    firstName:Sarah,
    lastname:Doe,
    fields:[{
        value: xyz,
        field_id: 1
    }]
}]

I would also like to ask if this is a correct design to save the values of user defined custom fields?

I want to fetch the contacts using aggregation that has name "doe" and the field value of slug "field_one" is "abc". But I still want to display all the fields of each contact along with related data. I am expecting following

[{
    _id:1,
    firstName:John,
    lastname:Doe,
    fields:[{
        value: abc,
        slug:field_one,
        name: Field One
    },{
        value: xyz,
        slug:field_one,
        name: Field One
    }]
},...]
0

There are 0 best solutions below