quick question, do you know if mongo can create an index on the following data:
{
prices: {
price1: 0.90,
price2: 0.12,
price3: 0.13
}
}
so I would like to do index like this ensureIndex({prices:1}) but I am not sure will it include all prices and its values inside.
The reason why I need to lay data this way not the standard Array approach is because I would like to be able to sort based on which price version has been chosen i.e. sort({prices.price:1}).
Any ideas?
cheers
Ok I think I understand now. You want sort all documents in a collection by a given price version.
This won’t work too well with subdocuments since you can’t do a positional sort as such:
As such this would be better as a flat structure within the root document. Infact in your example placing it in a subdocument has no real use other than to group the data which actually makes indexing harder.
So I would recommend you just project the fields to the root document. You can do something fancy with the aggregation framework here with @Philipp’s answer but it sounds like this query might be run extremely often and maybe on larger working sets.
As such the new document strucutre would be:
This is how I do this kind of stuff in both SQL and MongoDB and it works well with a compound index on all the fields.
As well since MongoDB is, of course, schemaless you don’t have to worry about maintaining the database when you want to add new prices to your app.