Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

แทรกฟิลด์เอกสาร MongoDB เฉพาะเมื่อมันหายไปหรือไม่


ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -

>db.missingDocumentDemo.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fb1eedc6604c74817ce6")
}
>db.missingDocumentDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fb29edc6604c74817ce7")
}
>db.missingDocumentDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3fb40edc6604c74817ce8")
}

ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -

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

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5cd3fb1eedc6604c74817ce6"),
   "StudentFirstName" : "Adam",
   "StudentLastName" : "Smith"
}
{
   "_id" : ObjectId("5cd3fb29edc6604c74817ce7"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor"
}
{
   "_id" : ObjectId("5cd3fb40edc6604c74817ce8"),
   "StudentFirstName" : "David",
   "StudentLastName" : "Miller",
   "StudentAge" : 21
}

นี่คือแบบสอบถามเพื่อแทรกฟิลด์เอกสาร MongoDB เฉพาะเมื่อขาดหายไป เรากำลังพยายามแทรกฟิลด์ StudentAge ที่นี่ มันจะไม่แทรกฟิลด์หากมีอยู่แล้ว -

> db.missingDocumentDemo.update(
...   { "StudentAge": { "$exists": false } },
...   { "$set": { "StudentAge": 23 } },
...   { "multi": true }
... );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

ให้เราแสดงเอกสารทั้งหมดจากคอลเลกชันข้างต้น -

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

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5cd3fb1eedc6604c74817ce6"),
   "StudentFirstName" : "Adam",
   "StudentLastName" : "Smith",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cd3fb29edc6604c74817ce7"),
   "StudentFirstName" : "Carol",
   "StudentLastName" : "Taylor",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cd3fb40edc6604c74817ce8"),
   "StudentFirstName" : "David",
   "StudentLastName" : "Miller",
   "StudentAge" : 21
}