Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để sử dụng toán tử 'Không thích' trong MongoDB?

Đối với điều này, hãy sử dụng toán tử $ not trong MongoDB. Để hiểu khái niệm, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

> db.notLikeOperatorDemo.insertOne({"StudentName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29c393b406bd3df60dfc")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29cc93b406bd3df60dfd")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"John Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a29df93b406bd3df60dfe")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"Carol Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a2a1693b406bd3df60dff")
}
> db.notLikeOperatorDemo.insertOne({"StudentName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a2a2693b406bd3df60e00")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

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

Sau đây là kết quả -

{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{
   "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"),
   "StudentName" : "John Smith"
}
{
   "_id" : ObjectId("5c8a29df93b406bd3df60dfe"),
   "StudentName" : "John Taylor"
}
{
   "_id" : ObjectId("5c8a2a1693b406bd3df60dff"),
   "StudentName" : "Carol Taylor"
}
{
   "_id" : ObjectId("5c8a2a2693b406bd3df60e00"),
   "StudentName" : "David Miller"
}

Đây là truy vấn sử dụng toán tử NOT LIKE trong MongoDB -

> db.notLikeOperatorDemo.find( { StudentName: { $not: /^John Taylor.*/ } } );

Sau đây là kết quả -

{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{ "_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }
You can use the following query also:
> db.notLikeOperatorDemo.find({StudentName: {$not: /John Taylor/}});
The following is the output:
{ "_id" : ObjectId("5c8a29c393b406bd3df60dfc"), "StudentName" : "John Doe" }
{ "_id" : ObjectId("5c8a29cc93b406bd3df60dfd"), "StudentName" : "John Smith" }
{ "_id" : ObjectId("5c8a2a1693b406bd3df60dff"), "StudentName" : "Carol Taylor" }
{ "_id" : ObjectId("5c8a2a2693b406bd3df60e00"), "StudentName" : "David Miller" }