goonieiam
goonieiam

Reputation: 77

mongodb/mongoose find common elements in two arrays

Assuming the following schema:

var user = {
    books : [{bookId : {type: String, ref: 'Book'}}]
};

and the following data :

user1.books[{bookId : 'id1'}, {bookId : 'id2'}]
user2.books[{bookId : 'id2'}]

what's the best way to find the intersection between user1 and user2 books? a query that would tell me that user1 and user2 have one book in common with bookId: 'id2'.

Thank you.

Upvotes: 1

Views: 1401

Answers (1)

ZeMoon
ZeMoon

Reputation: 20274

You can use aggregation for the same:

//Assuming the user model is named User
User.aggregate([
    {$match: {_id: {$in: [user1._id, user2._id]}}},
    {$group: {_id: 0, books1: {$first: "$books"}, books2: {$last: "$books"}}},
    {$project: {commonBooks: {$setIntersection: ["$books1","$books2"]}, _id: 0}}
], function(err, res) {
    console.log(err, res);
});

Note that this query can find common books only between two people.

Upvotes: 2

Related Questions