user1837378
user1837378

Reputation: 171

Select documents from one collection based on IDs stored in another in Meteor and MongoDB

I have three collections, Users (Meteor built-in), Movies, and Seen. A document in Seen consists of a movie ID (the movie's ID in the Movies collection) and a user ID (analogous), indicating that that user has seen that movie.

I want to get only those movies (documents) in the Movies collection which the current user has seen.

I know how to select the documents from Seen whose user IDs match the current user's ID. Do I make an array of the movie IDs from this row and then use Mongo's $in operator? What's the best way to do this?

Upvotes: 2

Views: 620

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

You've got the basic approach right:

var seenIds = Seen.find({ userId: Meteor.userId() }).map(function(doc){return doc.movieId});
var seenMovies = Movies.find({_id: {$in: seenIds}});

Upvotes: 1

chridam
chridam

Reputation: 103355

As you already mentioned, you can use the documents from the Seen collection whose user IDs match the current user's ID to make an array of movie IDs that you can then query with on the Movies collection. Something like the following:

var seen = Seen.find({ "userId": Meteor.userId() }).fetch(); // get Seen documents
var movieIds = seen.map(function (s){ return s.movieId; }); // get seen movie IDs list
var seenMovies = Movies.find({"_id": { "$in": movieIds }}).fetch(); // get the seen movies
console.log(JSON.stringify(seenMovies, null, 4));

Upvotes: 2

Related Questions