在MongoDB中处理可选/空数据?
为了处理空数据,可以使用$ne运算符。让我们创建包含文档的集合。以下是查询
>db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John","StudentCountryName":""});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cbd5ca629b87623db1b12")
}
>db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John","StudentCountryName":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cbd6ba629b87623db1b13")
}
> db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9cbd71a629b87623db1b14")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.handlingAndEmptyDataDemo.find().pretty();
这将产生以下输出
{
   "_id" : ObjectId("5c9cbd5ca629b87623db1b12"),
   "StudentName" : "John",
   "StudentCountryName" : ""
}
{
   "_id" : ObjectId("5c9cbd6ba629b87623db1b13"),
   "StudentName" : "John",
   "StudentCountryName" : null
}
{ "_id" : ObjectId("5c9cbd71a629b87623db1b14"), "StudentName" : "John" }以下是使用$ne处理空数据的查询
> db.handlingAndEmptyDataDemo.find({StudentCountryName: {$ne: null}});这将产生以下输出
{ "_id" : ObjectId("5c9cbd5ca629b87623db1b12"), "StudentName" : "John", "StudentCountryName" : "" }