Applying condition to multiple documents for the same field in MongoDB

前端 未结 1 338
悲哀的现实
悲哀的现实 2021-01-20 02:02

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,  ta         


        
相关标签:
1条回答
  • 2021-01-20 02:47

    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"}]})
    
    0 讨论(0)
提交回复
热议问题