Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Kiểm tra giá trị tồn tại cho trường trong document MongoDB?

Dùng find() kết hợp toán tử $exists. Tạo collection:

> db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98") }
> db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99") }
> db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a") }
> db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b") }

Hiển thị tất cả:

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

Kết quả:

{ "_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"), "PlayerName" : "John Smith", "PlayerScores" : [ 5000, 98595858, 554343 ] }
{ "_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"), "PlayerName" : "John Doe", "PlayerScores" : [ ] }
{ "_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"), "PlayerName" : "Carol Taylor", "PlayerScores" : [ 7848474, 8746345353 ] }
{ "_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"), "PlayerName" : "David Miller", "PlayerScores" : [ ] }

Kiểm tra document có mảng PlayerScores không rỗng (có phần tử tại index 0):

> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count();

Kết quả: 2 (2 document có mảng không rỗng).