MongoDB query 2

Array conditional query to find movies in 2012 and 2017

 

As long as there is one of China or Japan in the country array, the match is successful and the entire document is returned

 

To increase the elements of the array, use update and push to add new elements to the array, and duplicate values ​​can be added

db.stu.update(
    {'name':'aaa'},
    {$push:{
         'score':5
        }}
)

 

Use update and addToSet to add elements to the array, if the element exists, it will not be added

db.stu.update(
    {name:'aaa'},
    {$addToSet:{
        score:4
        }}
)

 

 

Query the movie tag array, the element attribute contains the movie whose name value is animation

 

Use $push to display the movie name of each segment

 

Find the number of movies with an animation tag

 

Query the number of movies with animations in two attribute arrays, use or

 

Multiple grouping query, query the number of different rated movies per year, use mapReduce

Using the aggregate function aggregate is much faster than mapReduce, but lacks customization, such as being unable to handle missing fields

 

Use mapReduce to calculate the number of movies in each segment, the default summary field uses value

 

Use aggregate to achieve the same effect, but more efficient and faster

 

  • Calculate the consumption amount of each user on the day of 2016-06-01, first find the records with consumption on this date, then use the user id as the key of the grouping, the cost as the values, and input it into reduce for summarization
db.consume.mapReduce(
    function(){ emit( this.user_id,this.price ) },
    function(key,values){ 
      var total = 0 ;
      for(var i=0;i<values.length;i++){
        total += values[i];
      }
       return total;
    },//end reduce function
    {
        query:{"date":"2016-06-01"}
    }
)


 

 

Multi-condition grouping, aggregate the data in the consume collection according to the amount of each customer per day

var mapfunction = function(){
    emit( {this.date, this.user_id},this.price} )
}

var reducefunction = function(key,values){ 
      var total = 0 ;
      for(var i=0;i<values.length;i++){
        total += values[i];
      }
      return total;
 }

db.consume.mapReduce(
    mapfunction,
    reducefunction
)


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325003445&siteId=291194637