在 MongoDB $in 中设置正则表达式?


让我们创建一个带有文档的集合 -

> db.demo675.insertOne({
... "ListOfNames":["John","Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5b404263e90dac943ef")
}
> db.demo675.insertOne({ "ListOfNames":["Bob","Johnson","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5c804263e90dac943f0")
}
> db.demo675.insertOne({ "ListOfNames":["Jace","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5d304263e90dac943f1")
}

在集合中使用 find() 方法显示所有文档 -

> db.demo675.find();

这将产生以下输出 -

{ "_id" : ObjectId("5ea3f5b404263e90dac943ef"), "ListOfNames" : [ "John", "Chris", "David" ] }
{ "_id" : ObjectId("5ea3f5c804263e90dac943f0"), "ListOfNames" : [ "Bob", "Johnson", "Sam" ] }
{ "_id" : ObjectId("5ea3f5d304263e90dac943f1"), "ListOfNames" : [ "Jace", "Sam" ] }

以下是使用正则表达式和数组进行查询的查询 -

> db.demo675.find({"ListOfNames": {$in:[/John/,/J/]}});

这将产生以下输出 -

{ "_id" : ObjectId("5ea3f5b404263e90dac943ef"), "ListOfNames" : [ "John", "Chris", "David" ] }
{ "_id" : ObjectId("5ea3f5c804263e90dac943f0"), "ListOfNames" : [ "Bob", "Johnson", "Sam" ] }
{ "_id" : ObjectId("5ea3f5d304263e90dac943f1"), "ListOfNames" : [ "Jace", "Sam" ] }

更新于:13-5-2020

116 次浏览

开启 职业生涯

通过完成课程获得认证

开始
广告