简体   繁体   中英

MongoDB multi indexing

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 ie sort({prices.price:1}) .

Any ideas?

cheers

When you do ensureIndex({prices:1}) on that data, you would create an index over the exact combination of price1, price2 and price3. So the index would only be searchable when you search for an exact match of all three prices together (no additional prices in either the search or the potential result).

But you could search for individual prices when you structure your data like that:

{
    prices: [
         {version: 1, value: 0.99},
         {version: 2, value: 0.12},
         {version: 3, value: 0.13}
    ]
}

You could then add a compound index which includes prices.version, prices.value and an unique identifier from the parent document. That way you could quickly search for products by {prices.version:1} or {prices.version:2} .

See also the documentation of indices in mongodb .

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:

find({price.version:1}).sort({price.$.version: 1})

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:

{
        price1: 0.90,
        price2: 0.12,
        price3: 0.13
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM