SlideShare a Scribd company logo
MongoDB + JS
Для начинающих
Темы:
● JS на стороне сервера (NodeJS)
● Подключение к базе MongoDB
● Запросы к базе
● Добавление документов
● Изменение документов
● Удаление документов
● Проекции
● Агрегации
MongoDB + JS. Mongo-клиенты
● Mongo Shell - https://docs.mongodb.com/getting-started/shell/installation/
● Robomongo - https://robomongo.org/
● UMongo - http://edgytech.com/umongo/
● Mongoclient - http://www.mongoclient.com/
MongoDB + JS. Вводная
node -v
npm install mongodb --save
npm -v
node main.js // в командной строке в директории с файлом main.js
MongoDB + JS. Подключение к базе
// main.js
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/grades', function(err, db) {
if(err) throw err;
console.log("Успешное подключение к базе");
db.close();
});
MongoDB + JS. Поиск записей - find()
var query = {}; // Поиск всех записей
var cursor = db.collection('grades').find(query);
cursor.each(function(err, doc) {
if(err) throw err;
if(doc == null) {
return db.close();
}
console.dir(doc.student_id);
});
MongoDB + JS. Поиск записей по параметру
var query = {student_id: 0}; // Поиск записей, где student_id = 0
var query = {student_id: 0, class_id: 2}; // Поиск записей, где student_id = 0 и
class_id = 2
MongoDB + JS. Поиск записей по параметру
var query = { $or: [ { student_id: 0 }, { class_id: 2 } ] }; // or
var query = { $and: [ { student_id: 0 }, { class_id: 2 } ] }; // and
// $or, $and, $in
// $or versus $in
var query = { $or: [ { student_id: 0 }, { student_id: 2 } ] };
query = { student_id: { $in: [0, 2] } };
MongoDB + JS. Поиск записей по параметру
var query = { '$regex': 'NSA' }; // regex
var query = { 'profession': { '$exists': true }}; // exists
// $regexes, $exists, $type
MongoDB + JS. Поиск записей по параметру
var query = {'media.oembed.type': 'video'}; // Вложенный поиск
var query = { 'scores.type': 'exam' }; // Вложенный поиск
MongoDB + JS. Поиск записей по параметру
var query = { 'grade': { '$gt': 10, '$lt': 20 } }; // Поиск записей, где
10 < grade < 20
var query = {student_id: 0, 'grade': { '$gt': 10, '$lt': 20 } }; // Поиск записей,
где student_id = 0 и 10 < grade < 20
var query = { name: { '$gte': 'F', '$lte': 'Q' }}; // Поиск записей, по name
от F до Q
var query = { student_id: { $eq: 2 } }; // eq
MongoDB + JS. Проекции
db.collection('grades').find(query, {student_id: true, class_id: true, _id: false}
) // projection - вывод значений, второй параметр в find
var query = {'media.oembed.type': 'video'}; // Вложенный поиск
var projection = {'media.oembed.type': 1, '_id': 0}; // Проекция
MongoDB + JS. Поиск записи - findOne()
// findOne.js - Вывести одну запись
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if(err) throw err;
var query = {student_id: 0}; // Поиск ОДНОЙ записи, где student_id = 0
db.collection('grades').findOne(query, function(err, doc) {
if(err) throw err;
console.dir(doc);
db.close();
});
});
MongoDB + JS. Cursor - Skip, Limit, Sort
var cursor = db.collection('grades').find({});
cursor.skip(1);
cursor.limit(4);
cursor.sort('grade', 1); // [[‘grade’], [student_id: -1]]
cursor.each(function(err, doc) {
//...
})
// или запишем по другому
var grades = db.collection('grades');
var options = { 'skip': 1, 'limit': 4, 'sort': [['grade',1], ['student_id', -1]] }
var cursor = grades.find({}, {}, options);
//cursor.skip(1);
//cursor.limit(4);
//cursor.sort('grade', 1);
cursor.each(function(err, doc) {
//...
})
MongoDB + JS. Добавление документов
var doc = { 'student' : 'Calvin', 'age' : 6 }; // добавление с без id
db.collection('students').insert(doc, function(err, inserted) {
// ...
});
var doc = { '_id' : 'calvin', 'age' : 6 }; // добавление с указанием id
var doc = [ { 'student' : 'Calvin', 'age' : 6 },
{ 'student' : 'Susie', 'age' : 7 } ]; // добавление массива значений
MongoDB + JS. Изменение документов
var query = { 'assignment' : 'hw1' };
var operator = { '$set' : { 'date_returned' : new Date() } }; // $set и $unset
var options = {};
db.collection('grades').update(query, operator, options, function(err, updated) {
//
});
var options = { 'multi' : true };
MongoDB + JS. Удаление документов
MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
if(err) throw err;
var query = { 'assignment' : 'hw3' };
db.collection('grades').remove(query, function(err, removed) {
if(err) throw err;
console.dir("Successfully updated " + removed + " documents!");
return db.close();
});
});
MongoDB + JS. Aggregation
var query = [
{'$match': {'student_id': 2}},
{'$unwind': '$scores'},
{'$match': {'scores.type': 'exam'}}, {
'$group': {
'_id': '$scores.type',
'exam count': {'$sum': 1}
}
}];
db.collection('grades').aggregate(query, function(err, doc) {
// ...
});
https://docs.mongodb.com/manual/reference/operator/aggregation/
Полезные ссылки:
http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/
http://mongodb.github.io/node-mongodb-native/2.2/tutorials/
https://docs.mongodb.com/manual/reference/operator/aggregation/
Контакты:
Mail: akonovalov@at-consulting.com
FB: https://www.facebook.com/sancho.konovalov
Skype: s2dent_73

More Related Content

What's hot (20)

PDF
Basis.js - Production Ready SPA Framework
MoscowJS
 
PPTX
Как мы документируем программные интерфейсы. YaC 2014
Yandex
 
PDF
Ruby exceptions
Andrei Kaleshka
 
PPTX
I tmozg js_school
ITmozg
 
PDF
"CommonJS для браузера", Антон Шувалов, MoscowJS 15
MoscowJS
 
PDF
Почему Mojolicious?
Anatoly Sharifulin
 
PDF
Making Scalable JavaScript Application
Mikhail Davydov
 
PDF
"Dependency Injection. JavaScript.", Сергей Камардин, MoscowJS 15
MoscowJS
 
PDF
«Изоморфные js приложения с использованием catberry.js», Денис Речкунов
DevDay
 
PDF
Дмитрий Щадей "Зачем и как мы используем jsLint"
Yandex
 
PDF
11 - Web-технологии. Работа с СУБД
Roman Brovko
 
PPT
Web осень 2012 лекция 4
Technopark
 
PPTX
PHP Advanced
Noveo
 
PDF
Modules and assembling of JavaScript (in russian)
Mikhail Davydov
 
PDF
Как запилить 80 React форм и иногда бывать дома
Andrew Smirnov
 
PPTX
Не верь никому или разработка эффективных приложений (Как писать по настоящем...
Moscow.pm
 
PPTX
Динамический код: модифицируем таблицу символов во время выполнения. Елена Ши...
Moscow.pm
 
PDF
django cheBit'11
dva
 
PPTX
Ruby - или зачем мне еще один язык программирования?
Pavel Tsukanov
 
PDF
10 - Web-технологии. MVC фреймворки (продолжение)
Roman Brovko
 
Basis.js - Production Ready SPA Framework
MoscowJS
 
Как мы документируем программные интерфейсы. YaC 2014
Yandex
 
Ruby exceptions
Andrei Kaleshka
 
I tmozg js_school
ITmozg
 
"CommonJS для браузера", Антон Шувалов, MoscowJS 15
MoscowJS
 
Почему Mojolicious?
Anatoly Sharifulin
 
Making Scalable JavaScript Application
Mikhail Davydov
 
"Dependency Injection. JavaScript.", Сергей Камардин, MoscowJS 15
MoscowJS
 
«Изоморфные js приложения с использованием catberry.js», Денис Речкунов
DevDay
 
Дмитрий Щадей "Зачем и как мы используем jsLint"
Yandex
 
11 - Web-технологии. Работа с СУБД
Roman Brovko
 
Web осень 2012 лекция 4
Technopark
 
PHP Advanced
Noveo
 
Modules and assembling of JavaScript (in russian)
Mikhail Davydov
 
Как запилить 80 React форм и иногда бывать дома
Andrew Smirnov
 
Не верь никому или разработка эффективных приложений (Как писать по настоящем...
Moscow.pm
 
Динамический код: модифицируем таблицу символов во время выполнения. Елена Ши...
Moscow.pm
 
django cheBit'11
dva
 
Ruby - или зачем мне еще один язык программирования?
Pavel Tsukanov
 
10 - Web-технологии. MVC фреймворки (продолжение)
Roman Brovko
 

Similar to Основы MongoDB + NodeJS (20)

PPT
MongoDB. Фокус на тестирование
Uladzimir Kryvenka
 
PPT
MongoDB basics in Russian
Oleg Kachan
 
PPTX
MongoDB. Области применения, преимущества и узкие места, тонкости использован...
phpdevby
 
PDF
MongoDB@addconf
Sergei Tulentsev
 
PPTX
MongoDB первые впечатления
fudz1k
 
PDF
Моделирование для NoSQL БД
Andrew Sovtsov
 
PDF
Встраивание языка в строковой интерполятор
Michael Limansky
 
PPT
Introduction to MongoDB
Iurii Ogiienko
 
ODP
Новое в Mongodb 2.4
Gleb Lebedev
 
ODP
Кратко о MongoDB
Gleb Lebedev
 
PPTX
MongoDB в продакшен - миф или реальность?
Alexey Tokar
 
PPTX
MongoDB - About Performance Optimization, Ivan Griga - Smart Gamma
Evgeniy Kuzmin
 
PDF
Практическое применение MongoDB Aggregation Framework
Денис Кравченко
 
PDF
Базы данных. MongoDB
Vadim Tsesko
 
PDF
Nosql and Mongodb
Eduard Antsupov
 
PDF
Продвинутое использование ActiveRecord в Yii2
Paul Klimov
 
PPTX
Sphinx + MongoDB: работаем вместе.
MageCloud
 
PPTX
Alasql.js - SQL сервер на JavaScript
Andrey Gershun
 
PDF
NoSQL pain
Ivan Grishaev
 
ODP
Поиск текста в MongoDB 2.4
Gleb Lebedev
 
MongoDB. Фокус на тестирование
Uladzimir Kryvenka
 
MongoDB basics in Russian
Oleg Kachan
 
MongoDB. Области применения, преимущества и узкие места, тонкости использован...
phpdevby
 
MongoDB@addconf
Sergei Tulentsev
 
MongoDB первые впечатления
fudz1k
 
Моделирование для NoSQL БД
Andrew Sovtsov
 
Встраивание языка в строковой интерполятор
Michael Limansky
 
Introduction to MongoDB
Iurii Ogiienko
 
Новое в Mongodb 2.4
Gleb Lebedev
 
Кратко о MongoDB
Gleb Lebedev
 
MongoDB в продакшен - миф или реальность?
Alexey Tokar
 
MongoDB - About Performance Optimization, Ivan Griga - Smart Gamma
Evgeniy Kuzmin
 
Практическое применение MongoDB Aggregation Framework
Денис Кравченко
 
Базы данных. MongoDB
Vadim Tsesko
 
Nosql and Mongodb
Eduard Antsupov
 
Продвинутое использование ActiveRecord в Yii2
Paul Klimov
 
Sphinx + MongoDB: работаем вместе.
MageCloud
 
Alasql.js - SQL сервер на JavaScript
Andrey Gershun
 
NoSQL pain
Ivan Grishaev
 
Поиск текста в MongoDB 2.4
Gleb Lebedev
 
Ad

Основы MongoDB + NodeJS

  • 1. MongoDB + JS Для начинающих
  • 2. Темы: ● JS на стороне сервера (NodeJS) ● Подключение к базе MongoDB ● Запросы к базе ● Добавление документов ● Изменение документов ● Удаление документов ● Проекции ● Агрегации
  • 3. MongoDB + JS. Mongo-клиенты ● Mongo Shell - https://docs.mongodb.com/getting-started/shell/installation/ ● Robomongo - https://robomongo.org/ ● UMongo - http://edgytech.com/umongo/ ● Mongoclient - http://www.mongoclient.com/
  • 4. MongoDB + JS. Вводная node -v npm install mongodb --save npm -v node main.js // в командной строке в директории с файлом main.js
  • 5. MongoDB + JS. Подключение к базе // main.js var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/grades', function(err, db) { if(err) throw err; console.log("Успешное подключение к базе"); db.close(); });
  • 6. MongoDB + JS. Поиск записей - find() var query = {}; // Поиск всех записей var cursor = db.collection('grades').find(query); cursor.each(function(err, doc) { if(err) throw err; if(doc == null) { return db.close(); } console.dir(doc.student_id); });
  • 7. MongoDB + JS. Поиск записей по параметру var query = {student_id: 0}; // Поиск записей, где student_id = 0 var query = {student_id: 0, class_id: 2}; // Поиск записей, где student_id = 0 и class_id = 2
  • 8. MongoDB + JS. Поиск записей по параметру var query = { $or: [ { student_id: 0 }, { class_id: 2 } ] }; // or var query = { $and: [ { student_id: 0 }, { class_id: 2 } ] }; // and // $or, $and, $in // $or versus $in var query = { $or: [ { student_id: 0 }, { student_id: 2 } ] }; query = { student_id: { $in: [0, 2] } };
  • 9. MongoDB + JS. Поиск записей по параметру var query = { '$regex': 'NSA' }; // regex var query = { 'profession': { '$exists': true }}; // exists // $regexes, $exists, $type
  • 10. MongoDB + JS. Поиск записей по параметру var query = {'media.oembed.type': 'video'}; // Вложенный поиск var query = { 'scores.type': 'exam' }; // Вложенный поиск
  • 11. MongoDB + JS. Поиск записей по параметру var query = { 'grade': { '$gt': 10, '$lt': 20 } }; // Поиск записей, где 10 < grade < 20 var query = {student_id: 0, 'grade': { '$gt': 10, '$lt': 20 } }; // Поиск записей, где student_id = 0 и 10 < grade < 20 var query = { name: { '$gte': 'F', '$lte': 'Q' }}; // Поиск записей, по name от F до Q var query = { student_id: { $eq: 2 } }; // eq
  • 12. MongoDB + JS. Проекции db.collection('grades').find(query, {student_id: true, class_id: true, _id: false} ) // projection - вывод значений, второй параметр в find var query = {'media.oembed.type': 'video'}; // Вложенный поиск var projection = {'media.oembed.type': 1, '_id': 0}; // Проекция
  • 13. MongoDB + JS. Поиск записи - findOne() // findOne.js - Вывести одну запись var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { if(err) throw err; var query = {student_id: 0}; // Поиск ОДНОЙ записи, где student_id = 0 db.collection('grades').findOne(query, function(err, doc) { if(err) throw err; console.dir(doc); db.close(); }); });
  • 14. MongoDB + JS. Cursor - Skip, Limit, Sort var cursor = db.collection('grades').find({}); cursor.skip(1); cursor.limit(4); cursor.sort('grade', 1); // [[‘grade’], [student_id: -1]] cursor.each(function(err, doc) { //... }) // или запишем по другому var grades = db.collection('grades'); var options = { 'skip': 1, 'limit': 4, 'sort': [['grade',1], ['student_id', -1]] } var cursor = grades.find({}, {}, options); //cursor.skip(1); //cursor.limit(4); //cursor.sort('grade', 1); cursor.each(function(err, doc) { //... })
  • 15. MongoDB + JS. Добавление документов var doc = { 'student' : 'Calvin', 'age' : 6 }; // добавление с без id db.collection('students').insert(doc, function(err, inserted) { // ... }); var doc = { '_id' : 'calvin', 'age' : 6 }; // добавление с указанием id var doc = [ { 'student' : 'Calvin', 'age' : 6 }, { 'student' : 'Susie', 'age' : 7 } ]; // добавление массива значений
  • 16. MongoDB + JS. Изменение документов var query = { 'assignment' : 'hw1' }; var operator = { '$set' : { 'date_returned' : new Date() } }; // $set и $unset var options = {}; db.collection('grades').update(query, operator, options, function(err, updated) { // }); var options = { 'multi' : true };
  • 17. MongoDB + JS. Удаление документов MongoClient.connect('mongodb://localhost:27017/course', function(err, db) { if(err) throw err; var query = { 'assignment' : 'hw3' }; db.collection('grades').remove(query, function(err, removed) { if(err) throw err; console.dir("Successfully updated " + removed + " documents!"); return db.close(); }); });
  • 18. MongoDB + JS. Aggregation var query = [ {'$match': {'student_id': 2}}, {'$unwind': '$scores'}, {'$match': {'scores.type': 'exam'}}, { '$group': { '_id': '$scores.type', 'exam count': {'$sum': 1} } }]; db.collection('grades').aggregate(query, function(err, doc) { // ... }); https://docs.mongodb.com/manual/reference/operator/aggregation/

Editor's Notes

  • #5: This will download the MongoDB driver and add a dependency entry in your `package.json` file.
  • #8: !Попробовать в инструментах перечисленных выше
  • #9: When using indexes with $or queries, each clause of an $or can use its own index. Consider the following query: db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) To support this query, rather than a compound index, you would create one index on quantity and another index on price: db.inventory.createIndex( { quantity: 1 } ) db.inventory.createIndex( { price: 1 } ) Array Query Operators NOTE For details on specific operator, including syntax and examples, click on the specific operator to go to its reference page. Name Description $all Matches arrays that contain all elements specified in the query. $elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions. $size Selects documents if the array field is a specified size.
  • #10: Which of the following query expressions would match a document with 'Microsoft' anywhere in the 'title' field? Select all that apply.
  • #11: Use dot notation to construct a query that selects for a document with a 'name' of 'Steve' in the 'students' array. Put your answer in the box below. Please use double quotes when constructing your answer. Here is an example of a document that should match the query: { 'course' : 'M101JS', 'students' : [ { 'name' : 'Susan' }, { 'name' : 'Steve' } ] }
  • #12: $eq Matches values that are equal to a specified value. $gt Matches values that are greater than a specified value. $gte Matches values that are greater than or equal to a specified value. $lt Matches values that are less than a specified value. $lte Matches values that are less than or equal to a specified value. $ne Matches all values that are not equal to a specified value. $in Matches any of the values specified in an array. $nin Matches none of the values specified in an array.
  • #13: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/projections/ Projections By default, queries in MongoDB return all fields in matching documents. To limit the amount of data that MongoDB sends to applications, you can include a projection document in the query operation. Projection Document The projection document limits the fields to return for all matching documents. The projection document can specify the inclusion of fields or the exclusion of field and has the following form: { field1: <value>, field2: <value> ... } <value> may be 0 (or false) to exclude the field, or 1 (or true) to include it. With the exception of the _id field, you may not have both inclusions and exclusions in the same projection document. Examples The following code example uses the restaurants sample dataset. To return only the name, cuisine and _id fields for documents which match the query filter, explicitly include the name and cuisine fields in the projection document. The _id field is included automatically unless specifically excluded. var MongoClient = require('mongodb').MongoClient , assert = require('assert'); // Connection URL var url = 'mongodb://localhost:27017/test'; // Use connect method to connect to the server MongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected correctly to server"); findDocuments(db, function() { db.close(); }); }); var findDocuments = function(db, callback) { // Get the documents collection var collection = db.collection( 'restaurants' ); // Find some documents collection.find({ 'cuisine' : 'Brazilian' }, { 'name' : 1, 'cuisine' : 1 }).toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); console.log(docs) callback(docs); }); } To return name and cuisine but exclude all other fields, including _id, use the following projection document: { 'name' : 1, 'cuisine' : 1, '_id': 0 } To return all fields except the address field, use the following: { 'address' : 0 }
  • #14: !Попробовать в инструментах перечисленных выше
  • #15: !Попробовать в инструментах перечисленных выше
  • #16: !Попробовать в инструментах перечисленных выше
  • #17: Update Operators Fields Name Description $inc Increments the value of the field by the specified amount. $mul Multiplies the value of the field by the specified amount. $rename Renames a field. $setOnInsert Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents. $set Sets the value of a field in a document. $unset Removes the specified field from a document. $min Only updates the field if the specified value is less than the existing field value. $max Only updates the field if the specified value is greater than the existing field value. $currentDate Sets the value of a field to current date, either as a Date or a Timestamp. Array Operators Name Description $ Acts as a placeholder to update the first element that matches the query condition in an update. $addToSet Adds elements to an array only if they do not already exist in the set. $pop Removes the first or last item of an array. $pullAll Removes all matching values from an array. $pull Removes all array elements that match a specified query. $pushAll Deprecated. Adds several items to an array. $push Adds an item to an array. Modifiers Name Description $each Modifies the $push and $addToSet operators to append multiple items for array updates. $slice Modifies the $push operator to limit the size of updated arrays. $sort Modifies the $push operator to reorder documents stored in an array. $position Modifies the $push operator to specify the position in the array to add elements. update() Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria. upsert boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found. multi boolean Optional. If set to true, updates multiple documents that meet the querycriteria. If set to false, updates one document. The default value is false. For additional information, see Multi Parameter. findAndModify() Modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option. The findAndModify() method is a shell helper around the findAndModifycommand. The findAndModify() method has the following form:
  • #18: !Попробовать в инструментах перечисленных выше
  • #19: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/aggregation/ Aggregation Overview Aggregation operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. The Aggregation Pipeline The aggregation pipeline is a framework for data aggregation modeled on the concept of data processing pipelines. Documents enter a multi-stage pipeline that transforms the documents into aggregated results. For a full explanation and a complete list of pipeline stages and operators, see the manual: The following example uses the aggregation pipeline on the restaurant sample dataset to find a list of restaurants located in the Bronx, grouped by restaurant category. var MongoClient = require('mongodb').MongoClient , assert = require('assert'); var url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function(err, db) { assert.equal(null, err); simplePipeline(db, function() { db.close(); }); }); var simplePipeline = function(db, callback) { var collection = db.collection( 'restaurants' ); collection.aggregate( [ { '$match': { "borough": "Bronx" } }, { '$unwind': '$categories'}, { '$group': { '_id': "$categories", 'Bronx restaurants': { '$sum': 1 } } } ], function(err, results) { assert.equal(err, null); console.log(results) callback(results); } ); } Inside the aggregate method, the first pipeline stage filters out all documents except those with 5 in the stars field. The second stage unwinds the categories field, which is an array, and treats each item in the array as a separate document. The third stage groups the documents by category and adds up the number of matching 5-star results. Single Purpose Aggregation Operations MongoDB provides helper methods for some aggregation functions, including count, group, and distinct. Count The following example demonstrates how to use the count method to find the total number of documents which have the exact array [ 'Chinese', 'Seafood' ] in the categories field. var MongoClient = require('mongodb').MongoClient , assert = require('assert'); var url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function(err, db) { assert.equal(null, err); simpleCount(db, function() { db.close(); }); }); var simpleCount = function(db, callback) { var collection = db.collection( 'restaurants' ); collection.count({ 'categories': [ 'Chinese', 'Seafood' ] }, function(err, result) { assert.equal(err, null); console.log(result) callback(result); } ); } Group The following example uses the group method with four arguments: an array of fields to group by a document with conditions for filterings an initial results document a reduce function The example groups the results by number of stars where the categories array is ['Peruvian']. var MongoClient = require('mongodb').MongoClient , assert = require('assert'); var url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function(err, db) { assert.equal(null, err); simpleGroup(db, function() { db.close(); }); }); var simpleGroup = function(db, callback) { var collection = db.collection( 'restaurants' ); collection.group( ['stars'], { 'categories': ['Peruvian'] }, { 'total': 0 }, "function ( curr, result ) { result.total++ }", function(err, result) { assert.equal(err, null); console.log(result) callback(result); } ); } Distinct The distinct helper method eliminates results which contain values and returns one record for each unique value. The following example returns a list of unique values for the categories field in the restaurantscollection: var MongoClient = require('mongodb').MongoClient , assert = require('assert'); var url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function(err, db) { assert.equal(null, err); simpleDistinct(db, function() { db.close(); }); }); var simpleDistinct = function(db, callback) { var collection = db.collection( 'restaurants' ); collection.distinct( 'categories', function(err, result) { assert.equal(err, null); console.log(result) callback(result); } ); }