ericyue
ericyue

Reputation: 656

How to Query this in MongoDB?

My items store in MongoDB like this :

{"ProductName":"XXXX",
   "Catalogs" : [
    {
        "50008064" : "Apple"
    },
    {
        "50010566" : "Box"
    },
    {
        "50016422" : "Water"
    }
]}

Now I want query all the items belong to Catalog:50008064,how to? (the catalog id "50008064" , catalog name "Apple")

Upvotes: 0

Views: 86

Answers (2)

Remon van Vliet
Remon van Vliet

Reputation: 18595

You cannot query this in an efficient manner and performance will decrease as your data grows. As such I would consider it a schema bug and you should refactor/migrate to the following model which does allow for indexing :

{"ProductName":"XXXX",
   "Catalogs" : [
    {
        id : "50008064",
        value : "Apple"
    },
    {
        id : "50010566",
        value : "Box"
    },
    {
        id : "50016422",
        value : "Water"
    }
]}

And then index :

ensureIndex({'Catalogs.id':1})

Again, I strongly suggest you change your schema as this is a potential performance bottleneck you cannot fix any other way.

Upvotes: 3

kufi
kufi

Reputation: 2458

This should probably work according to the entry here, although this won't be very fast, as stated in in the link.

db.products.find({ "Catalogs.50008064" : { $exists: true } } )

Upvotes: 0

Related Questions