Reputation: 953
I have an an array of objects which contain an artist, a song title and some other data, for example:
var obj = {
artist: 'Of Monsters and Men',
title: 'Little Talks',
data: 'important thing'
}
var array = [<obj1>, <obj2>, <obj3>];
I have also a mongoDB collection with contain songs. I need to query this collection and return all the songs which have the artist AND the title contained in the previous array. I also need to access the data field of the matching object.
I used to loop in the array and perform a query for each objects but it consumes too much resources, as there can be hundreds/thousands of objects in the array. Is there a way to achieve it?
Upvotes: 2
Views: 185
Reputation: 4383
As @vmr suggested, you could change your schema, but in case you don't want to, here are a few options:
You could use the aggregation framework.
`db.collection.aggregate( { $group: {
_id:{artist:"$artist", title:"$title"},
data:{$push:"$data"}
}, function(err, result){})`
** Remember ** The resultant document must be less than 16MB.
Or, you could open a cursor like so
db.collections.find({ artist: 'some artist', title: 'some title'}, function(err, cursor){ //don't call .toArray()
function handleItem(err, item){
if(item == null) return;
//do stuff...
cursor.nextObject(handleItem);
}
cursor.nextObject(handleItem);
})
This would most certainly cut down your iterator, and since each document is already less than 16 MB you won't have to worry about an aggregated document being too large
Upvotes: 3
Reputation: 1935
The ideal way to solve this problem would be to re-design the schema: The document schema should look something like this:
{ artist: 'Of Monsters and Men',
title: 'Little Talks',
data: 'important thing'
songs: [{song1 details},{song2 details},....] }
This way retrieval will be much faster as you need to access a single document for an artist.
Upvotes: 2