1

I would like to construct a query that will return just the names of the classes for the datastructure below. So far, the closest I've come is using dot notation

db.mycoll.find({name:"game1"},{"classes.1.name":true})

But the problem with this approach is that it will only return the name of the first class. Please help me get the names of all three classes.

I wish I could use a wild card as below, but I'm not sure if that exists.

db.mycoll.find({name:"game1"},{"classes.$*.name":true})

Datastructure:

{
"name" : "game1",
"classes" : {
    "1" : {
        "name" : "warlock",
        "version" : "1.0"
    },
    "2" : {
        "name" : "shaman",
        "version" : "2.0"
    },
    "3" : {
        "name" : "mage",
        "version" : "1.0"
    }
}
2
  • 1
    Have you considered making classes an array instead of an embedded doc with numerical properties? That would be the traditional approach.
    – JohnnyHK
    Jul 31, 2012 at 18:49
  • I have, but for our use case a map is desireable for efficiency reasons. Jul 31, 2012 at 20:18

1 Answer 1

1

There is no simple query that will achieve the results you seek. MongoDB has limited support for querying against sub-objects or arrays of objects. The basic premise with MongoDB is that you are querying for the top-level document.

That said, things are changing and you still have some options:

  1. Use the new MongoDB Aggregation Framework. This has a $project operation that should do what you're looking for.
  2. You can return just the classes field and then merge the names together. This should be trivial with most languages.

Note, that it's not clear what you're doing with classes. Is this an array or an object? If it's an object, what does classes.1 actually represent? Is it different from classes.warlock?

3
  • I'm attempting suggestion 2 at the moment. I was unaware of the Aggregation Framework. Thanks for the suggestion :) It's an object. 1 is the id of the object, and name (and many other fields and sub-objects actually) is part of the object's metadata. Jul 31, 2012 at 20:21
  • Mr. Gates VP, Might I trouble you for a sample of how you were thinking of using the $project operator? Jul 31, 2012 at 20:28
  • Well, if classes is an array, then you can $unwind: '$classes' and $project: { 'name': 1 }. However, the unwind does not work with objects. It looks like the 1 is an object, so the aggregation framework will probably not work here.
    – Gates VP
    Jul 31, 2012 at 23:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.