Find and replace NumberLong type field in MongoDB?


Use $set operator along with update() for this. Let us first create a collection with documents. Here we have set one field as NumberLong −

> db.findAndReplaceDemo.insertOne({"UserId":NumberLong(101)});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2c960b64f4b851c3a13b6")
}
> db.findAndReplaceDemo.insertOne({"UserId":NumberLong(110)});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2c966b64f4b851c3a13b7")
}
> db.findAndReplaceDemo.insertOne({"UserId":NumberLong(101)});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2c969b64f4b851c3a13b8")
}
> db.findAndReplaceDemo.insertOne({"UserId":NumberLong(120)});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2c96cb64f4b851c3a13b9")
}
> db.findAndReplaceDemo.insertOne({"UserId":NumberLong(130)});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2c96eb64f4b851c3a13ba")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.findAndReplaceDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cd2c960b64f4b851c3a13b6"), "UserId" : NumberLong(101) }
{ "_id" : ObjectId("5cd2c966b64f4b851c3a13b7"), "UserId" : NumberLong(110) }
{ "_id" : ObjectId("5cd2c969b64f4b851c3a13b8"), "UserId" : NumberLong(101) }
{ "_id" : ObjectId("5cd2c96cb64f4b851c3a13b9"), "UserId" : NumberLong(120) }
{ "_id" : ObjectId("5cd2c96eb64f4b851c3a13ba"), "UserId" : NumberLong(130) }

Following is the query to find and replace NumberLong type field in MongoDB −

> db.findAndReplaceDemo.update({"UserId":NumberLong(101)}, {$set:{"UserId":NumberLong(10001)}},false,true);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Let us check the updated result from the above collection −

> db.findAndReplaceDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd2c960b64f4b851c3a13b6"),
   "UserId" : NumberLong(10001)
}
{    "_id" : ObjectId("5cd2c966b64f4b851c3a13b7"),
   "UserId" : NumberLong(110)
}
{
   "_id" : ObjectId("5cd2c969b64f4b851c3a13b8"),
   "UserId" : NumberLong(10001)
}
{
   "_id" : ObjectId("5cd2c96cb64f4b851c3a13b9"),
   "UserId" : NumberLong(120)
}
{
   "_id" : ObjectId("5cd2c96eb64f4b851c3a13ba"),
   "UserId" : NumberLong(130)
}

Updated on: 30-Jul-2019

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements