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:
- Automobiles
- Airplanes
- Boats
- Bicycles
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:
- This is a very different problem than trying to do a JOIN in Mongo -- or, at least it could be. (See: MongoDB - Search on multiple collections. I'm not trying to correlate documents from different collections as I would in a JOIN. (E.g., it cannot be said that documents in the Boats collection contain details about documents in the Automobiles collection.)
- There appears to be a poor solution out there that would involve running the query for each collection (i.e., query five Automobiles, five Airplanes, five Boats, and five Bicycles; merge the results into an array, sort by createdAt, and then splice the first five off the front of the array). See: Meteor.js - ways to do user search over multiple collections. However, if possible, I'd like to avoid this because (i) it will make the queries 5x less efficient; and (ii) it will make pagination VERY difficult.
- I am using Sails.js as my framework (and, hence, Waterline as my ORM). So, even if this isn't possible at the Mongo layer, I theorize that it may have been implemented at the ORM layer. Is that so, and, if so, how would I use it?