Query BinData by Type in MongoDB

MongoDBDatabaseBig Data Analytics

To query by type, use subtype() in MongoDB. Let us create a collection with documents −

> db.demo249.insertOne({ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv") });
{
   "acknowledged" : true,
   "insertedId" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv")
}
> db.demo249.insertOne({"_id" : BinData(4,"CNDF66qIlCY92q1vFAAAAQ==")});
{
   "acknowledged" : true,
   "insertedId" : UUID("08d0c5eb-aa88-9426-3dda-ad6f14000001")
}
> db.demo249.insertOne({"_id" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==")});
{
   "acknowledged" : true,
   "insertedId" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==")
}

Display all documents from a collection with the help of find() method −

> db.demo249.find();

This will produce the following output −

{ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv") }
{ "_id" : UUID("08d0c5eb-aa88-9426-3dda-ad6f14000001") }
{ "_id" : BinData(3,"CNDF66qJ29g92q1vFAAAEw==") }

Following is how to query BinData by Type −

> db.demo249.find(function(){ return this._id.subtype() == 0 });

This will produce the following output −

{ "_id" : BinData(0,"AQAAAAEBAAVlbl9VSwAAAAAAAAhv")
raja
Published on 30-Mar-2020 14:09:48
Advertisements