开发者

Searching within array within particular document in mongodb

I have a collection of the following sort of documents (taken from Mongo DB Docs: Schema Design for familiarity):

db.students
{ name: 'Jane',
  scores: [
              { course: 'math', grade: 'A'},
              { course: 'biology', grade: 'B'},
              { course: 'english', grade: 'C'}
          ]
}

If I already have the document for Jane, what is the best way to retrieve her grade for e.g. math?

The only guidance I have been able to find in the docs concerns finding, for example, all the students with grade A for math, but in this case I already have the student document I want to query.

The only way I have seen to access arrays is through array index, e.g. scores[0].grade, but I do not necessarily know the array index.

Thanks

edit: I am aware that I could simply lo开发者_运维百科op through the array to find the correct entry, but I was wondering if there was a better way.


Unfortunately, there's no straightforward way to do this type of query in MongoDB. The new $slice operator will help you limit what number of scores that come back, but obviously that's only useful if you know the position of the course you want.

I asked a similar question on the Mongo Google Group...

http://groups.google.com/group/mongodb-user/browse_thread/thread/ec7144cf03d8e724/d09f5b8eb9d6a990?lnk=gst&q=%24slice#d09f5b8eb9d6a990


If you are using the 2.2 version of MongoDB, you can use the 'match' aggregation function:

See here for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜