How to create composite key in Mongodb

Asked

Viewed 393 times

1

How can I create composite key in Mongodb and use in C#?

  • If I don’t know, but why would someone do that?

  • 4

    Make an object like Primary key that contains 2 values, for example: { _id : { a : 1, b: 1} }.

  • It’s a necessity. Why wouldn’t I, @LINQ ?

  • @fajuchem, it worked here. Thank you!

1 answer

2


As mentioned by @fajuchen, nothing prevents you from populating _id with a compound object:

{
    _id: { 
        a: 'b99c514b-cb23-4b42-8710-a69db774c904',
        b: '1caf0d2f-3f03-4287-a8ed-65c77f1d0ef4'
    }
}

This is the best option if you can guarantee that access to documents will always be by the composite key.

If not, it might be worth considering creating a secondary index mapped to a property with the content of the composite key:

{
    _id: 'ff1a5f39-bdea-4d25-b473-0a15d9602963',
    key: { 
        a: 'b99c514b-cb23-4b42-8710-a69db774c904',
        b: '1caf0d2f-3f03-4287-a8ed-65c77f1d0ef4'
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.