Group operations for MongoDB

Source: Internet
Author: User
Insert test data first:

For (VAR I = 1; I <20; I ++ ){

VaR num = I % 6;

DB. Test. insert ({_ ID: I, name: "User _" + I, age: num });

}

1. Common grouping query (http://www.my400800.cn)

DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){

Prev. Num ++

}});

DB. runcommand ({group:

{

NS: "test ",

Key: {age: true },

Initial: {num: 0 },

$ Reduce: function (Doc, Prev ){

Prev. Num ++}

}

});

2. filter and then group

DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){

Prev. Num ++

},

Condition: {age :{$ GT: 2 }}

});

DB. runcommand ({group:

{

NS: "test ",

Key: {age: true },

Initial: {num: 0 },

$ Reduce: function (Doc, Prev ){

Prev. Num ++ },

Condition: {age :{$ GT: 2 }}

}

});

Common $ where queries:

DB. Test. Find ({$ where: function (){

Return this. age> 2;

}

});

Group join $ where Query

DB. Test. Group ({key: {age: true}, initial: {num: 0}, $ reduce: function (Doc, Prev ){

Prev. Num ++

},

Condition: {$ where: function (){

Return this. age> 2;

}

}

});

3. grouping with function return values

// Note that the $ keyf specified function must return an object.

DB. test. group ({$ keyf: function (DOC) {return {age: Doc. age };}, initial: {num: 0}, $ reduce: function (Doc, Prev ){

Prev. Num ++

}

});

DB. runcommand ({group:

{

NS: "test ",

$ Keyf: function (DOC) {return {age: Doc. Age };},

Initial: {num: 0 },

$ Reduce: function (Doc, Prev ){

Prev. Num ++}

}

});

4. Use the Terminator

DB. test. group ({$ keyf: function (DOC) {return {age: Doc. age };}, initial: {num: 0}, $ reduce: function (Doc, Prev ){

Prev. Num ++

},

Finalize: function (DOC) {Doc. Count = Doc. Num; Delete Doc. Num ;}

});

DB. runcommand ({group:

{

NS: "test ",

$ Keyf: function (DOC) {return {age: Doc. Age };},

Initial: {num: 0 },

$ Reduce: function (Doc, Prev ){

Prev. Num ++ },

Finalize: function (DOC) {Doc. Count = Doc. Num; Delete Doc. Num ;}

}

});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.