I have a single-page application that is feeding on an API I wrote in JavasScript running on Node.js and using MongoDB for data storage. The API exposes several different content types, each of which is stored in a separate collection in my MongoDB database. My single-page application has a search bar consisting of a drop-down to select content type (each one corresponding to a distinct collection in my MongoDB database) and an input field to specify a search query that will be applied.
What I would like to do is: add an option in my dropdown, called "All", and, when this is selected, my API will return the five most-recently created documents, regardless of the collection that contains those documents.
So, as an example, I might have the following collections:
I would like to write JavaScript in my API that returns the most recent five of any of these. As such, if the user searches for "G", the JSON response that I generate might contain several documents from each collection, as follows:
[
{
"_id": "123",
"name": "Golf,
"collection: "Automobile",
"createdAt": "2014-06-20T01:45:00.0000Z"
},
{
"_id": "234",
"name": Gulfstream",
"collection": "Airplane",
"createdAt": "2014-06-19T01:45:00.0000Z"
},
{
"_id": "345",
"name": "Glastron",
"collection": "Boat",
"createdAt": "2014-06-18T01:45:00.0000Z"
},
{
"_id": "456",
"name": "Gary Fisher",
"collection" "Bicycle",
"createdAt": "2014-06-17T01:45:00.0000Z"
}
{
"_id": "567",
"name": "Grand Prix",
"collection": "Automobile",
"createdAt": "2014-06-16T01:45:00.0000Z"
}
]
Question: Is searching across multiple collections possible in Mongo, and, if so, how do I do it?
Please note:
Though John Petrone's comment is very helpful (as it points out that I am running up against a limitation in Mongo), I did want to put together a comprehensive list of possible solutions: