Reputation: 4144
I'm using Meteor and MongoDB, as suggested by the documentation. Coming from a relational database background, I want to understand strategies for modeling data in NOSQL stores.
The scenario is I have users
, and each user
has one vin
. All pretty standard and possible with one collection. But if I want to find the highest vin
to display some anonymous information about the most recently purchased car, do I just construct a find like:
Users.find({}, sort: {vin_number: -1})
or is there a better way to model it? What if a given user has more than one vin
? In a relational world, that's a "has many" relationship. But if I embed an array of vins
in a user document, how could I extract the highest number.
As you can see, I am wrestling with the fundamental shift from modeling things as tables to embedded documents.
Any help is appreciated, and (although I know it's not the SO way) I'd love any pointers to places for a gentle migration from the relational modeling patterns to schema-less ones.
Upvotes: 1
Views: 275
Reputation: 7343
For array fields you can use instruction $unwind
at aggregation framework. It create different items from your one and you can easily filtrate it as usual.
For example you have item similar to this one:
{_id: 'KJDKDSJKSJDK', type: 'car', manufacturer: 'opel', model: 'vectra', vins: [1234,5678]}
unwind will create two new items for this projection:
{_id: 'KJDKDSJKSJDK', type: 'car', manufacturer: 'opel', model: 'vectra', vins: 1234}
{_id: 'KJDKDSJKSJDK', type: 'car', manufacturer: 'opel', model: 'vectra', vins: 5678}
As you can see array field changed to int.
Upvotes: 1
Reputation: 75945
You could use a transform to get the highest vin from the list of vins:
Users.find({}, {sort: {vin_number: -1}, transform: function(doc) {
doc.vin_number = _.max(doc.vin_number_array);
return doc;
}})
I've never tried this, i'm a bit unsure of whether the transform or the sort comes first. But if you had an array of vin numbers in vin_number_array
in your document, the vin_number
would end up as the highest of those using underscore's max
function.
Upvotes: 1