I have a documents with the following structure:
user {id: 123, tag:"tag1"}
user {id: 123, tag:"tag2"}
user {id: 123, tag:"tag3"}
user {id: 456, tag:"tag1"}
Given user id I want to find if this user has records with all 3 tags (AND operand). If user has records for "tag1" AND "Tag2" AND "tag3" then return true
SQL equivalent would be like this:
SELECT * FROM users WHERE
EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag1') AND
EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag2') AND
user_id=123
How can I express something simular in MongoDB?
Because MongoDB does not have a concept of joins, you need to work across this by reducing your input to a single document.
If you change your document structure so that you are storing an array of tags, like the following:
{id: 123, tag:["tag1","tag2","tag3"]}
{id: 456, tag:["tag1"]}
You can do a query like the following:
db.user.find({$and:[{tag:"tag1"},{tag:"tag2"},{tag:"tag3"}]})
If needed, you could write a map-reduce to emit an array of tags for a userid, so you can do the above query on it.
Edit - Including a simple map-reduce
Here is a really simple map-reduce to get the initial input into a format that is useful for the find
query given above.
var map = function() {emit(this.id, {tag:[this.tag]});}
var reduce = function(key, values){
var result_array=[];
values.forEach(function(v1){
v1.tag.forEach(function(v2){
result_array.push(v2);
});
});
return {"tag":result_array};}
var op = db.user.mapReduce(map, reduce, {out:"mr_results"})
Then you can query on the map-reduce output collection, like the following:
db.mr_results.find({$and:[{"value.tag":"tag1"},{"value.tag":"tag2"}, {"value.tag":"tag3"}]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With