একটি MongoDB সংগ্রহের প্রতিটি নথিতে নতুন ক্ষেত্র যোগ করতে, আপনি $set অপারেটর ব্যবহার করতে পারেন। সিনট্যাক্স নিম্নরূপ:
db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true); উপরের সিনট্যাক্স বোঝার জন্য, আসুন কিছু নথি সহ একটি সংগ্রহ তৈরি করি। ডকুমেন্ট সহ একটি সংগ্রহ তৈরি করার প্রশ্নটি নিম্নরূপ:
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"John","StudentAddress":"US
"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906ae")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"David","StudentAddress":"U
K"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906af")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Carol","StudentAddress":"U
K"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906b0")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Bob","StudentAddress":"US"
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6efc0b6fd07954a48906b1")
} Find() পদ্ধতির সাহায্যে একটি সংগ্রহ থেকে সমস্ত নথি প্রদর্শন করুন। প্রশ্নটি নিম্নরূপ:
> db.addNewFieldToEveryDocument.find().pretty();
নিম্নলিখিত আউটপুট:
{
"_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
"StudentName" : "John",
"StudentAddress" : "US"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906af"),
"StudentName" : "David",
"StudentAddress" : "UK"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
"StudentName" : "Carol",
"StudentAddress" : "UK"
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
"StudentName" : "Bob",
"StudentAddress" : "US"
} প্রতিটি নথিতে একটি নতুন ক্ষেত্র যোগ করার জন্য নিম্নোক্ত ক্যোয়ারী:
> db.addNewFieldToEveryDocument.update({}, { $set: {"StudentAge": 24} }, false, true);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 }) উপরে, আমরা প্রতিটি ডকুমেন্টে একটি নতুন ফিল্ড “StudentAge”:24 যুক্ত করেছি। আসুন আমরা ফিল্ডটি পরীক্ষা করি যে “স্টুডেন্টএজ”:24 প্রতিটি নথিতে সফলভাবে যুক্ত হয়েছে কি না। প্রশ্নটি নিম্নরূপ:
> db.addNewFieldToEveryDocument.find().pretty();
নিম্নলিখিত আউটপুট:
{
"_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
"StudentName" : "John",
"StudentAddress" : "US",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906af"),
"StudentName" : "David",
"StudentAddress" : "UK",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
"StudentName" : "Carol",
"StudentAddress" : "UK",
"StudentAge" : 24
}
{
"_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
"StudentName" : "Bob",
"StudentAddress" : "US",
"StudentAge" : 24
}