Reputation: 1926
I'm quite new to Meteor and its Mongo DB, and I'm wondering how I could find 'related documents'.
I have a collection of posts, that has tags, like this:
[{ title : 'title', tags: [{name : 'tag1'}, {name : 'tag2'}]}]
Now I want to query my database, to find posts that have an intersection on these tag set, where I want to order the results by size of the intersection descending.
How should this be encoded into a find() query, where the query is given an array of tags to check against as input?
Upvotes: 1
Views: 890
Reputation: 19544
It's easy with this structure:
[{
title: 'title',
tags: ['tag1', 'tag2'],
}]
Then you use:
Documents.find({
tags: {$all: [ "alpha", "beta", "gamma" ]}
});
See here: http://docs.mongodb.org/manual/reference/operator/all/#op._S_all
Now, it may or may not work with complex objects as you have, I'm not sure. Try this:
Documents.find({
tags: {$all: [{name: "alpha"}, {name: "beta"}]}
});
If you need the specified structure and the above query does not work, you're left with the $where
query. It is very flexible, but not recommended as it's much slower than the others. See here:
http://docs.mongodb.org/manual/reference/operator/where/#op._S_where
EDIT: this one should do the job:
Documents.find({
'tags.name': {$all: ["alpha", "beta"]}
});
Upvotes: 0
Reputation: 5578
You can also find simply as:
Collection.find({"tags.name" : "tag1"})
This will give all matching documents that have 'tag1'
in the tags
array.
Upvotes: 1