如何在 MongoDB 中处理可选/空数据?

mongodbdatabasebig data analytics更新于 2026/1/16 15:37:17

为了处理空数据,您可以使用 $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" : "" }

相关文章