I am working with a fairly complex data structure, which I am storing in mongodb. The document, as these are known in the parlance of Mongo, contains six embedded documents, one of which is an array of documents.
It is this document, the array, which I am interested in searching.
The mongo home page is a great resource for us mongo-nubs — the documentation available there is well-written, clear, and concise. Sometimes, I can even find what I need, before I even realize that I need it!
However, like most documentation, and this is the former support-engineer in me talking, developer documentation is written in a tone of a “solution” and not as a “problem”. In other words, when I’m looking to solve a problem I am having, I am searching in the terms of my problem. Once I’ve solved the problem, I will usually document what I’ve learned — the challenge is to not write the document using the vocabulary of the solution, but to use the vocabulary of the problem (seeking) instead.
Anyway, the problem statement for this entry is to be able to search a field within an array of fields within an embedded document, within a mongodb document. Here we go….
My data structure looks something like this:
In PHP, I’d access the element using a syntax similar to:
Assuming that I’m spinning through the data-structure under some looping control mechanism. What threw me off here, when accessing the structure using Mongo’s BSON notation, was the concept of the array index.
Basically, from my understanding, there is none. The Mongo webs site quote:
Reaching into arrays is implicit: if the field being queried is an array, the database automatically assumes the caller intends to look for a value within the array…
…gave me the clue I needed to write the query correctly: you don’t assume an array index since Mongo does it for you.
fetches all records where the last name = ‘Shallop’ when that last name appears in any of the 10 array positions within the ‘members’ structure.
While I don’t believe that the full impact of this has settled in, I immediately appreciate the aspect of not having to worry about array indexing while traversing deeper into my Mongo documents…