如何在MongoDB中使用$ type?

$type选择文档,其中字段的值是指定BSON类型的实例。让我们创建一个包含文档的集合-

> db.demo615.insert({"Value":100});
WriteResult({ "nInserted" : 1 })
> db.demo615.insert({"Value":"100"});
WriteResult({ "nInserted" : 1 })
> db.demo615.insert({"Value":"300"});
WriteResult({ "nInserted" : 1 })
> db.demo615.insert({"Value":300});
WriteResult({ "nInserted" : 1 })

find()方法的帮助下显示集合中的所有文档-

> db.demo615.find();

这将产生以下输出-

{ "_id" : ObjectId("5e99bb3465492f6c60d0027f"), "Value" : 100 }
{ "_id" : ObjectId("5e99bb3865492f6c60d00280"), "Value" : "100" }
{ "_id" : ObjectId("5e99bb3c65492f6c60d00281"), "Value" : "300" }
{ "_id" : ObjectId("5e99bb4265492f6c60d00282"), "Value" : 300 }

以下是使用不含十六进制_id的MongoDB find的查询-

> db.demo615.find({ "Value" : { $type : "string"} } );

这将产生以下输出-

{ "_id" : ObjectId("5e99bb3865492f6c60d00280"), "Value" : "100" }
{ "_id" : ObjectId("5e99bb3c65492f6c60d00281"), "Value" : "300" }