0

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")

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

then how to query the catalogs ? like this ?db.products.find({ "Catalogs.50008064" : { $exists: true } } )
No, like db.products.find({'Catalogs.id':50008064}) which is a lot cleaner and faster.
0

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 } } )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.