Saturday, 5 June 2021

Mongo shell: forEach method to iterate over a cursor

‘forEach’ method is used to iterate over a cursor and apply a function to each document from the cursor.

 

Example

db.countryCapitals.find().forEach((doc) => {printjson(doc)})

> db.countryCapitals.find().forEach((doc) => {printjson(doc)})
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed2"),
    "country" : "Afghanistan",
    "city" : "Kabul"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed3"),
    "country" : "Albania",
    "city" : "Tirana"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed4"),
    "country" : "Algeria",
    "city" : "Alger"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed5"),
    "country" : "American Samoa",
    "city" : "Fagatogo"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed6"),
    "country" : "Andorra",
    "city" : "Andorra la Vella"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed7"),
    "country" : "Angola",
    "city" : "Luanda"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed8"),
    "country" : "Anguilla",
    "city" : "The Valley"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ed9"),
    "country" : "Antarctica",
    "city" : null
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3eda"),
    "country" : "Antigua and Barbuda",
    "city" : "Saint John's"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3edb"),
    "country" : "Argentina",
    "city" : "Buenos Aires"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3edc"),
    "country" : "Armenia",
    "city" : "Yerevan"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3edd"),
    "country" : "Aruba",
    "city" : "Oranjestad"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ede"),
    "country" : "Australia",
    "city" : "Canberra"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3edf"),
    "country" : "Austria",
    "city" : "Wien"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee0"),
    "country" : "Azerbaijan",
    "city" : "Baku"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee1"),
    "country" : "Bahamas",
    "city" : "Nassau"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee2"),
    "country" : "Bahrain",
    "city" : "al-Manama"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee3"),
    "country" : "Bangladesh",
    "city" : "Dhaka"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee4"),
    "country" : "Barbados",
    "city" : "Bridgetown"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee5"),
    "country" : "Belarus",
    "city" : "Minsk"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee6"),
    "country" : "Belgium",
    "city" : "Bruxelles [Brussel]"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee7"),
    "country" : "Belize",
    "city" : "Belmopan"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee8"),
    "country" : "Benin",
    "city" : "Porto-Novo"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3ee9"),
    "country" : "Bermuda",
    "city" : "Hamilton"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3eea"),
    "country" : "Bhutan",
    "city" : "Thimphu"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3eeb"),
    "country" : "Bolivia",
    "city" : "La Paz"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3eec"),
    "country" : "Bosnia and Herzegovina",
    "city" : "Sarajevo"
}
{
    "_id" : ObjectId("60bbadbe8251689f64fb3eed"),
    "country" : "Botswana",
    "city" : "Gaborone"
}

 

 

 

Previous                                                    Next                                                    Home

Mongo shell: it: Get all the results from cursor

‘find()’ method return a cursor object, which is used to iterate over the results. By default, you will get 20 results max.

 

Let’s see it with an example.

 

countryCapitals.json

[
    {
        "country": "Afghanistan",
        "city": "Kabul"
    },
    {
        "country": "Albania",
        "city": "Tirana"
    },
    {
        "country": "Algeria",
        "city": "Alger"
    },
    {
        "country": "American Samoa",
        "city": "Fagatogo"
    },
    {
        "country": "Andorra",
        "city": "Andorra la Vella"
    },
    {
        "country": "Angola",
        "city": "Luanda"
    },
    {
        "country": "Anguilla",
        "city": "The Valley"
    },
    {
        "country": "Antarctica",
        "city": null
    },
    {
        "country": "Antigua and Barbuda",
        "city": "Saint John's"
    },
    {
        "country": "Argentina",
        "city": "Buenos Aires"
    },
    {
        "country": "Armenia",
        "city": "Yerevan"
    },
    {
        "country": "Aruba",
        "city": "Oranjestad"
    },
    {
        "country": "Australia",
        "city": "Canberra"
    },
    {
        "country": "Austria",
        "city": "Wien"
    },
    {
        "country": "Azerbaijan",
        "city": "Baku"
    },
    {
        "country": "Bahamas",
        "city": "Nassau"
    },
    {
        "country": "Bahrain",
        "city": "al-Manama"
    },
    {
        "country": "Bangladesh",
        "city": "Dhaka"
    },
    {
        "country": "Barbados",
        "city": "Bridgetown"
    },
    {
        "country": "Belarus",
        "city": "Minsk"
    },
    {
        "country": "Belgium",
        "city": "Bruxelles [Brussel]"
    },
    {
        "country": "Belize",
        "city": "Belmopan"
    },
    {
        "country": "Benin",
        "city": "Porto-Novo"
    },
    {
        "country": "Bermuda",
        "city": "Hamilton"
    },
    {
        "country": "Bhutan",
        "city": "Thimphu"
    },
    {
        "country": "Bolivia",
        "city": "La Paz"
    },
    {
        "country": "Bosnia and Herzegovina",
        "city": "Sarajevo"
    },
    {
        "country": "Botswana",
        "city": "Gaborone"
    }
]

Let’s insert above document into countryCapitals collection.

> db.countryCapitals.insert(
... [
...     {
...         "country": "Afghanistan",
...         "city": "Kabul"
...     },
...     {
...         "country": "Albania",
...         "city": "Tirana"
...     },
...     {
...         "country": "Algeria",
...         "city": "Alger"
...     },
...     {
...         "country": "American Samoa",
...         "city": "Fagatogo"
...     },
...     {
...         "country": "Andorra",
...         "city": "Andorra la Vella"
...     },
...     {
...         "country": "Angola",
...         "city": "Luanda"
...     },
...     {
...         "country": "Anguilla",
...         "city": "The Valley"
...     },
...     {
...         "country": "Antarctica",
...         "city": null
...     },
...     {
...         "country": "Antigua and Barbuda",
...         "city": "Saint John's"
...     },
...     {
...         "country": "Argentina",
...         "city": "Buenos Aires"
...     },
...     {
...         "country": "Armenia",
...         "city": "Yerevan"
...     },
...     {
...         "country": "Aruba",
...         "city": "Oranjestad"
...     },
...     {
...         "country": "Australia",
...         "city": "Canberra"
...     },
...     {
...         "country": "Austria",
...         "city": "Wien"
...     },
...     {
...         "country": "Azerbaijan",
...         "city": "Baku"
...     },
...     {
...         "country": "Bahamas",
...         "city": "Nassau"
...     },
...     {
...         "country": "Bahrain",
...         "city": "al-Manama"
...     },
...     {
...         "country": "Bangladesh",
...         "city": "Dhaka"
...     },
...     {
...         "country": "Barbados",
...         "city": "Bridgetown"
...     },
...     {
...         "country": "Belarus",
...         "city": "Minsk"
...     },
...     {
...         "country": "Belgium",
...         "city": "Bruxelles [Brussel]"
...     },
...     {
...         "country": "Belize",
...         "city": "Belmopan"
...     },
...     {
...         "country": "Benin",
...         "city": "Porto-Novo"
...     },
...     {
...         "country": "Bermuda",
...         "city": "Hamilton"
...     },
...     {
...         "country": "Bhutan",
...         "city": "Thimphu"
...     },
...     {
...         "country": "Bolivia",
...         "city": "La Paz"
...     },
...     {
...         "country": "Bosnia and Herzegovina",
...         "city": "Sarajevo"
...     },
...     {
...         "country": "Botswana",
...         "city": "Gaborone"
...     }
... ])
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 28,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})


db.collection.find() in the mongo shell automatically iterates the cursor to display up to the first 20 documents. Type 'it' to continue to get next batch results.

> db.countryCapitals.find()
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed2"), "country" : "Afghanistan", "city" : "Kabul" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed3"), "country" : "Albania", "city" : "Tirana" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed4"), "country" : "Algeria", "city" : "Alger" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed5"), "country" : "American Samoa", "city" : "Fagatogo" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed6"), "country" : "Andorra", "city" : "Andorra la Vella" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed7"), "country" : "Angola", "city" : "Luanda" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed8"), "country" : "Anguilla", "city" : "The Valley" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ed9"), "country" : "Antarctica", "city" : null }
{ "_id" : ObjectId("60bbadbe8251689f64fb3eda"), "country" : "Antigua and Barbuda", "city" : "Saint John's" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3edb"), "country" : "Argentina", "city" : "Buenos Aires" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3edc"), "country" : "Armenia", "city" : "Yerevan" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3edd"), "country" : "Aruba", "city" : "Oranjestad" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ede"), "country" : "Australia", "city" : "Canberra" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3edf"), "country" : "Austria", "city" : "Wien" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee0"), "country" : "Azerbaijan", "city" : "Baku" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee1"), "country" : "Bahamas", "city" : "Nassau" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee2"), "country" : "Bahrain", "city" : "al-Manama" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee3"), "country" : "Bangladesh", "city" : "Dhaka" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee4"), "country" : "Barbados", "city" : "Bridgetown" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee5"), "country" : "Belarus", "city" : "Minsk" }
Type "it" for more

Type"it" to get next 20 documents.

> it
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee6"), "country" : "Belgium", "city" : "Bruxelles [Brussel]" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee7"), "country" : "Belize", "city" : "Belmopan" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee8"), "country" : "Benin", "city" : "Porto-Novo" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3ee9"), "country" : "Bermuda", "city" : "Hamilton" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3eea"), "country" : "Bhutan", "city" : "Thimphu" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3eeb"), "country" : "Bolivia", "city" : "La Paz" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3eec"), "country" : "Bosnia and Herzegovina", "city" : "Sarajevo" }
{ "_id" : ObjectId("60bbadbe8251689f64fb3eed"), "country" : "Botswana", "city" : "Gaborone" }
>





 

 

Previous                                                    Next                                                    Home

Mongo shell: why pretty method fails on findOne method

‘pretty()’ method runs on a cursor. Since findOne() method do not return a cursor, pretty() method will not work on it.

> db.audit.findOne()
{
      "_id" : ObjectId("60bb0156baf44d88348459c4"),
      "type" : "login",
      "modifiedTimestamp" : 1622908612185
}
> 
> db.audit.findOne().pretty()
uncaught exception: TypeError: db.audit.findOne(...).pretty is not a function :
@(shell):1:1

Since find() method return a cursor, you can use pretty() method with find() method.

> db.audit.find().pretty()
{
      "_id" : ObjectId("60bb0156baf44d88348459c4"),
      "type" : "login",
      "modifiedTimestamp" : 1622908612185
}
{
      "_id" : ObjectId("60bb9c348251689f64fb3ece"),
      "type" : "logout",
      "client" : "browser",
      "userId" : 234,
      "createdTimestamp" : 1622907956987
}
{
      "_id" : ObjectId("60bb9c418251689f64fb3ecf"),
      "type" : "login",
      "modifiedTimestamp" : 1622908670676
}
{
      "_id" : ObjectId("60bb9c598251689f64fb3ed0"),
      "type" : "reset_credentials",
      "client" : "mobile",
      "userId" : 31,
      "createdTimestamp" : 1622907993918
}
{
      "_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
      "type" : "login",
      "client" : "mobile",
      "userId" : 41,
      "createdTimestamp" : 1622908015960,
      "modifiedTimestamp" : 1622908909572
}

 

 

 

Previous                                                    Next                                                    Home

Mongo shell: Convert find query results to an array

‘find().toArray()’ method converts the find() query results to an array. Since it loads all the matched documents into the memory, use toArray() method with caution.

> db.countryCapitals.find().toArray()
[
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed2"),
        "country" : "Afghanistan",
        "city" : "Kabul"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed3"),
        "country" : "Albania",
        "city" : "Tirana"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed4"),
        "country" : "Algeria",
        "city" : "Alger"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed5"),
        "country" : "American Samoa",
        "city" : "Fagatogo"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed6"),
        "country" : "Andorra",
        "city" : "Andorra la Vella"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed7"),
        "country" : "Angola",
        "city" : "Luanda"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed8"),
        "country" : "Anguilla",
        "city" : "The Valley"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ed9"),
        "country" : "Antarctica",
        "city" : null
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3eda"),
        "country" : "Antigua and Barbuda",
        "city" : "Saint John's"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3edb"),
        "country" : "Argentina",
        "city" : "Buenos Aires"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3edc"),
        "country" : "Armenia",
        "city" : "Yerevan"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3edd"),
        "country" : "Aruba",
        "city" : "Oranjestad"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ede"),
        "country" : "Australia",
        "city" : "Canberra"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3edf"),
        "country" : "Austria",
        "city" : "Wien"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee0"),
        "country" : "Azerbaijan",
        "city" : "Baku"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee1"),
        "country" : "Bahamas",
        "city" : "Nassau"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee2"),
        "country" : "Bahrain",
        "city" : "al-Manama"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee3"),
        "country" : "Bangladesh",
        "city" : "Dhaka"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee4"),
        "country" : "Barbados",
        "city" : "Bridgetown"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee5"),
        "country" : "Belarus",
        "city" : "Minsk"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee6"),
        "country" : "Belgium",
        "city" : "Bruxelles [Brussel]"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee7"),
        "country" : "Belize",
        "city" : "Belmopan"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee8"),
        "country" : "Benin",
        "city" : "Porto-Novo"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3ee9"),
        "country" : "Bermuda",
        "city" : "Hamilton"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3eea"),
        "country" : "Bhutan",
        "city" : "Thimphu"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3eeb"),
        "country" : "Bolivia",
        "city" : "La Paz"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3eec"),
        "country" : "Bosnia and Herzegovina",
        "city" : "Sarajevo"
    },
    {
        "_id" : ObjectId("60bbadbe8251689f64fb3eed"),
        "country" : "Botswana",
        "city" : "Gaborone"
    }
]

 

 

 

Previous                                                    Next                                                    Home

MongoDB: update vs updateMany

 ‘updateMany’ is used to update all the documents that matches to the given filter, whereas ‘update’ method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter. Let’s see it with an example.

> db.audit.find().pretty()
{
	"_id" : ObjectId("60bb0156baf44d88348459c4"),
	"type" : "login",
	"client" : "mobile",
	"userId" : 123,
	"createdTimestamp" : 1622868310979
}
{
	"_id" : ObjectId("60bb9c348251689f64fb3ece"),
	"type" : "logout",
	"client" : "browser",
	"userId" : 234,
	"createdTimestamp" : 1622907956987
}
{
	"_id" : ObjectId("60bb9c418251689f64fb3ecf"),
	"type" : "login",
	"client" : "browser",
	"userId" : 1,
	"createdTimestamp" : 1622907969953
}
{
	"_id" : ObjectId("60bb9c598251689f64fb3ed0"),
	"type" : "reset_credentials",
	"client" : "mobile",
	"userId" : 31,
	"createdTimestamp" : 1622907993918
}
{
	"_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
	"type" : "login",
	"client" : "mobile",
	"userId" : 41,
	"createdTimestamp" : 1622908015960
}
>

Update parameter like $set is mandatory for updateMany method.

 

For example,

> db.audit.updateMany({"type" : "login"}, {"type" : "signIn", "modifiedTimestamp" : Date.now()})
uncaught exception: Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateMany@src/mongo/shell/crud_api.js:655:19
@(shell):1:1


Try using $set parameter like below.

db.audit.updateMany({"type" : "login"}, {$set : {"type" : "signIn", "modifiedTimestamp" : Date.now()}})

> db.audit.updateMany({"type" : "login"}, {$set : {"type" : "signIn", "modifiedTimestamp" : Date.now()}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }
> 
> db.audit.find().pretty()
{
	"_id" : ObjectId("60bb0156baf44d88348459c4"),
	"type" : "signIn",
	"client" : "mobile",
	"userId" : 123,
	"createdTimestamp" : 1622868310979,
	"modifiedTimestamp" : 1622908523246
}
{
	"_id" : ObjectId("60bb9c348251689f64fb3ece"),
	"type" : "logout",
	"client" : "browser",
	"userId" : 234,
	"createdTimestamp" : 1622907956987
}
{
	"_id" : ObjectId("60bb9c418251689f64fb3ecf"),
	"type" : "signIn",
	"client" : "browser",
	"userId" : 1,
	"createdTimestamp" : 1622907969953,
	"modifiedTimestamp" : 1622908523246
}
{
	"_id" : ObjectId("60bb9c598251689f64fb3ed0"),
	"type" : "reset_credentials",
	"client" : "mobile",
	"userId" : 31,
	"createdTimestamp" : 1622907993918
}
{
	"_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
	"type" : "signIn",
	"client" : "mobile",
	"userId" : 41,
	"createdTimestamp" : 1622908015960,
	"modifiedTimestamp" : 1622908523246
}


If you do not provide update parameter ($set), update method replaces one matched document with the new document.

> db.audit.update({"type" : "signIn"}, {"type" : "login", "modifiedTimestamp" : Date.now()})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.audit.find().pretty()
{
	"_id" : ObjectId("60bb0156baf44d88348459c4"),
	"type" : "login",
	"modifiedTimestamp" : 1622908612185
}
{
	"_id" : ObjectId("60bb9c348251689f64fb3ece"),
	"type" : "logout",
	"client" : "browser",
	"userId" : 234,
	"createdTimestamp" : 1622907956987
}
{
	"_id" : ObjectId("60bb9c418251689f64fb3ecf"),
	"type" : "signIn",
	"client" : "browser",
	"userId" : 1,
	"createdTimestamp" : 1622907969953,
	"modifiedTimestamp" : 1622908523246
}
{
	"_id" : ObjectId("60bb9c598251689f64fb3ed0"),
	"type" : "reset_credentials",
	"client" : "mobile",
	"userId" : 31,
	"createdTimestamp" : 1622907993918
}
{
	"_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
	"type" : "signIn",
	"client" : "mobile",
	"userId" : 41,
	"createdTimestamp" : 1622908015960,
	"modifiedTimestamp" : 1622908523246
}


Let’s execute same update query again.

> db.audit.update({"type" : "signIn"}, {"type" : "login", "modifiedTimestamp" : Date.now()})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.audit.find().pretty()
{
	"_id" : ObjectId("60bb0156baf44d88348459c4"),
	"type" : "login",
	"modifiedTimestamp" : 1622908612185
}
{
	"_id" : ObjectId("60bb9c348251689f64fb3ece"),
	"type" : "logout",
	"client" : "browser",
	"userId" : 234,
	"createdTimestamp" : 1622907956987
}
{
	"_id" : ObjectId("60bb9c418251689f64fb3ecf"),
	"type" : "login",
	"modifiedTimestamp" : 1622908670676
}
{
	"_id" : ObjectId("60bb9c598251689f64fb3ed0"),
	"type" : "reset_credentials",
	"client" : "mobile",
	"userId" : 31,
	"createdTimestamp" : 1622907993918
}
{
	"_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
	"type" : "signIn",
	"client" : "mobile",
	"userId" : 41,
	"createdTimestamp" : 1622908015960,
	"modifiedTimestamp" : 1622908523246
}


If you provide $set update parameter, it updates the documents, instead of replacing.

> db.audit.update({"type" : "signIn"}, {$set : {"type" : "login", "modifiedTimestamp" : Date.now()}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.audit.find().pretty()
{
	"_id" : ObjectId("60bb0156baf44d88348459c4"),
	"type" : "login",
	"modifiedTimestamp" : 1622908612185
}
{
	"_id" : ObjectId("60bb9c348251689f64fb3ece"),
	"type" : "logout",
	"client" : "browser",
	"userId" : 234,
	"createdTimestamp" : 1622907956987
}
{
	"_id" : ObjectId("60bb9c418251689f64fb3ecf"),
	"type" : "login",
	"modifiedTimestamp" : 1622908670676
}
{
	"_id" : ObjectId("60bb9c598251689f64fb3ed0"),
	"type" : "reset_credentials",
	"client" : "mobile",
	"userId" : 31,
	"createdTimestamp" : 1622907993918
}
{
	"_id" : ObjectId("60bb9c6f8251689f64fb3ed1"),
	"type" : "login",
	"client" : "mobile",
	"userId" : 41,
	"createdTimestamp" : 1622908015960,
	"modifiedTimestamp" : 1622908909572
}










 

 

Previous                                                    Next                                                    Home

Friday, 4 June 2021

MongoDB: replaceOne: Replace one document

‘replaceOne’ method replace single document that matches to given filter criteria.

 

Signature

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     hint: <document|string>                   // Available starting in 4.2.1
   }
)

 

Example

db.employee.replaceOne({"lastName" : "nzv"}, {"deleted" : true, "deletedTime" : Date.now()})

 

Let’s experiment with employee collection.

> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c7"),
      "firstName" : "Rohini",
      "lastName" : "Shankar"
}
{
      "_id" : ObjectId("60bb06e6baf44d88348459c8"),
      "firstName" : "Trinadh",
      "lastName" : "nzv"
}
{
      "_id" : ObjectId("60bb07d3baf44d88348459c9"),
      "firstName" : "Shankar",
      "lastName" : "nzv"
}

Replace one document whose lastName is nzv.

> db.employee.replaceOne({"lastName" : "nzv"}, {"deleted" : true, "deletedTime" : Date.now()})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> 
> db.employee.find().pretty()
{
      "_id" : ObjectId("60bb035bbaf44d88348459c5"),
      "firstName" : "Sailja",
      "lastName" : "PTR",
      "active" : true,
      "modifiedTime" : 1622868890184
}
{
      "_id" : ObjectId("60bb062abaf44d88348459c7"),
      "firstName" : "Rohini",
      "lastName" : "Shankar"
}
{
      "_id" : ObjectId("60bb06e6baf44d88348459c8"),
      "deleted" : true,
      "deletedTime" : 1622870057702
}
{
      "_id" : ObjectId("60bb07d3baf44d88348459c9"),
      "firstName" : "Shankar",
      "lastName" : "nzv"
}




 

 

 

  

Previous                                                    Next                                                    Home

MongoDB: deleteMany: delete all the documents from a collection

‘db.collectionName.deleteMany({})’ statement delete all the documents from a collection.

 

Example

db.employee.deleteMany({})

> db.employee.find()
{ "_id" : ObjectId("60ba0a678e67ad0ff5b02998"), "firstName" : "Jessi" }
{ "_id" : ObjectId("60ba0b278e67ad0ff5b02999"), "id" : 34, "name" : "Anand", "age" : 42, "designation" : "Manager" }
{ "_id" : ObjectId("60baeb13baf44d88348459be"), "name" : "Krishna" }
> 
> db.employee.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 3 }
> 
> db.employee.find()
>

 

 

 

Previous                                                    Next                                                    Home