How to use mongodb

Comprehensive mongodb code examples:

How to use mongodb.Collection:

How to use mongodb.ReadPreference:

17
18
19
20
21
22
23
24
25
26
/*!
 * Module dependencies.
 */

var mongodb = require('mongodb');
var ReadPref = mongodb.ReadPreference;

/*!
 * Converts arguments to ReadPrefs the driver
 * can understand.

How to use mongodb.db:

22
23
24
25
26
27
28
29
30
31

Use dburl

```js
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/integration_tests", {native_parser:true});
db.bind('article');
db.article.find().toArray(function(err, items) {
        db.close();
});

How to use mongodb.ReplSetServers:

77
78
79
80
81
82
83
84
85
86
```js
var mongo = require('mongodb');
var Db = mongo.Db;
var Server = mongo.Server;
var MongoClient = mongo.MongoClient;
var ReplSetServers = mongo.ReplSetServers;
...
```

mongoskin:

How to use mongodb.BSONRegExp:

99
100
101
102
103
104
105
106
107
108
static async searchNews(keyword, result) {
    try {
        const query = {
            $or: [
                {
                    title: new BSONRegExp(`^.*${keyword}.*$`, "i")
                },
                {
                    category: new BSONRegExp(`^.*${keyword}.*$`, "i")
                },

How to use mongodb.PRIMARY:

168
169
170
171
172
173
174
175
176
177
];

/**
 * The default read preference.
 */
var READ_PREFERENCE_DEFAULT = ReadPreference.PRIMARY;

Object.assign(props, {
  /**
   * @property {String} authentication - `auth_mechanism` for humans.

How to use mongodb.NEAREST:

79
80
81
82
83
84
85
86
87
let myObjectReadPreference = null;
databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => {
  if (call.args[0].indexOf('MyObject') >= 0) {
    myObjectReadPreference = true;
    expect(call.args[2].readPreference.preference).toBe(
      ReadPreference.NEAREST
    );
  }
});

How to use mongodb.SECONDARY:

3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
.all()
.forEach(call => {
  if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) {
    foundGraphQLClassReadPreference = true;
    expect(call.args[0].options.readPreference.mode).toBe(
      ReadPreference.SECONDARY
    );
  } else if (call.args[0].ns.collection.indexOf('_User') >= 0) {
    foundUserClassReadPreference = true;
    expect(call.args[0].options.readPreference.mode).toBe(

How to use mongodb.Connection:

154
155
156
157
158
159
160
161
162

This is one of the ways to establish a connection to the MongoDB server in which the `db` variable will hold a reference to the database at a specified host and port:

```js
const Db = mongodb.Db
const Connection = mongodb.Connection
const Server = mongodb.Server
const host = '127.0.0.1'
const port = 27017

How to use mongodb.Code:

25
26
27
28
29
30
31
32
33
34
  return db
}

// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32
module.exports.Long = mongodb.Long

How to use mongodb.MaxKey:

30
31
32
33
34
35
36
37
38
39
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32
module.exports.Long = mongodb.Long
module.exports.MaxKey = mongodb.MaxKey
module.exports.MinKey = mongodb.MinKey
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID

How to use mongodb.Symbol:

35
36
37
38
39
40
41
42
43
module.exports.MaxKey = mongodb.MaxKey
module.exports.MinKey = mongodb.MinKey
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
module.exports.Map = mongodb.Map
module.exports.Decimal128 = mongodb.Decimal128

How to use mongodb.Map:

37
38
39
40
41
42
43
44
45
46
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
module.exports.Map = mongodb.Map
module.exports.Decimal128 = mongodb.Decimal128

// Add support for default ES6 module imports
module.exports.default = module.exports

How to use mongodb.Timestamp:

36
37
38
39
40
41
42
43
44
45
module.exports.MinKey = mongodb.MinKey
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
module.exports.Map = mongodb.Map
module.exports.Decimal128 = mongodb.Decimal128

// Add support for default ES6 module imports

How to use mongodb.MinKey:

31
32
33
34
35
36
37
38
39
40
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32
module.exports.Long = mongodb.Long
module.exports.MaxKey = mongodb.MaxKey
module.exports.MinKey = mongodb.MinKey
module.exports.NumberLong = mongodb.Long // Alias for shell compatibility
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID
module.exports.Symbol = mongodb.Symbol

How to use mongodb.Double:

27
28
29
30
31
32
33
34
35
36

// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32
module.exports.Long = mongodb.Long
module.exports.MaxKey = mongodb.MaxKey
module.exports.MinKey = mongodb.MinKey

How to use mongodb.Decimal128:

38
39
40
41
42
43
44
45
46
module.exports.ObjectId = mongodb.ObjectId
module.exports.ObjectID = mongodb.ObjectID
module.exports.Symbol = mongodb.Symbol
module.exports.Timestamp = mongodb.Timestamp
module.exports.Map = mongodb.Map
module.exports.Decimal128 = mongodb.Decimal128

// Add support for default ES6 module imports
module.exports.default = module.exports

How to use mongodb.DBRef:

26
27
28
29
30
31
32
33
34
35
}

// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32
module.exports.Long = mongodb.Long
module.exports.MaxKey = mongodb.MaxKey

How to use mongodb.createFromHexString:

185
186
187
188
189
190
191
192
193
194
      })
  })

// Update the dates and numReplies of the thread
mongo.db.collection('threads')
  .updateOne({ _id: new ObjectID.createFromHexString(req.params.id) },{
    $set: { 'lastPostBy': req.user.username, 'lastPostDate': date, 'lastPosterIsAdmin': newReply.posterIsAdmin },
    $inc: { 'numReplies': 1 }
  }, (err, result) => {
    if (err){console.log(err)}

How to use mongodb.Int32:

27
28
29
30
31
32
33
34
35
36
If you specifically need to store an integer as a 32-bit or 64-bit value, you can use a driver-specific method or construct BSON objects using the appropriate BSON data type for integers. For example, in the Node.js MongoDB driver, you can use the `Int32` and `Long` constructors from the `mongodb` package:

```javascript
const { Int32, Long } = require('mongodb');

const myInt32 = new Int32(42); // Creates a 32-bit integer
const myInt64 = new Long(9007199254740991); // Creates a 64-bit integer
```

Remember that choosing the appropriate integer size can help optimize storage and performance within your MongoDB application. Use `Int32` for smaller value ranges and `Int64` for larger value ranges as needed.

How to use mongodb.BSONPure:

1
2
3
4
5
6
7
8
9
10
declare var module;

var mongo = require('mongodb');
var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;
var curl = require('node-curl');

class LeaderBoardApi
{

How to use mongodb.Long:

28
29
30
31
32
33
34
35
36

```javascript
const { Int32, Long } = require('mongodb');

const myInt32 = new Int32(42); // Creates a 32-bit integer
const myInt64 = new Long(9007199254740991); // Creates a 64-bit integer
```

Remember that choosing the appropriate integer size can help optimize storage and performance within your MongoDB application. Use `Int32` for smaller value ranges and `Int64` for larger value ranges as needed.

How to use mongodb.Db:

153
154
155
156
157
158
159
160
161
162
```

This is one of the ways to establish a connection to the MongoDB server in which the `db` variable will hold a reference to the database at a specified host and port:

```js
const Db = mongodb.Db
const Connection = mongodb.Connection
const Server = mongodb.Server
const host = '127.0.0.1'
const port = 27017

How to use mongodb.Server:

155
156
157
158
159
160
161
162
163
164
This is one of the ways to establish a connection to the MongoDB server in which the `db` variable will hold a reference to the database at a specified host and port:

```js
const Db = mongodb.Db
const Connection = mongodb.Connection
const Server = mongodb.Server
const host = '127.0.0.1'
const port = 27017

const db = new Db ('test', new Server(host,port, {}))

How to use mongodb.GridFSBucket:

262
263
264
265
266
267
268
269
270
271
// Remove the post with the provided postId
const result = await Post.deleteOne({ _id: postId });

if (result.deletedCount === 1) {
  // Delete the image using GridFSBucket
  const bucket = new GridFSBucket(mongoose.connection.db, {
    bucketName: "posts",
  });

  // Find the image file in the posts.files collection

How to use mongodb.Binary:

24
25
26
27
28
29
30
31
32
33

  return db
}

// expose bson stuff visible in the shell
module.exports.Binary = mongodb.Binary
module.exports.Code = mongodb.Code
module.exports.DBRef = mongodb.DBRef
module.exports.Double = mongodb.Double
module.exports.Int32 = mongodb.Int32

How to use mongodb.isValid:

58
59
60
61
62
63
64
65
66
67
}

let permission;
let ownOnly = false;
permission = roles.can(req.role).readAny('userlisting');
if (!permission.granted && req.user && ObjectId.isValid(req.user)) {
    permission = roles.can(req.role).readOwn('userlisting');
    if (permission.granted) {
        ownOnly = true;
    }

How to use mongodb.ObjectID:

91
92
93
94
95
96
97
98
99
100

For example, in a Node.js code with the native driver use `ObjectID()`:

```js
const mongodb = require('mongodb')
const ObjectID = mongodb.ObjectID
collection.findOne({_id: new ObjectID(idString)}, console.log)
```

On the other hand, in the MongoDB shell and many other MongoDB libraries like Mongoose, we employ `ObjectId()`. The following is the MongoDB shell code:

How to use mongodb.connect:

67
68
69
70
71
72
73
74
75
76
event.setMaxListeners(20);


var mydb;
// Leave the connection open and reuse it.
new mc.connect(dbs, function(err, db) {
  if (!err) {
    db.on('close', function() {
         console.log('database CLOSED!, how to reopen???');
    });