MongoDB 查詢以查詢陣列中存在作為指定詞子串的字串的文件


對於此類評估,請在 MongoDB 中使用 aggregate()。我們建立一個帶有文件的集合 -

> db.demo90.insertOne(
... {"words": ["john", "jace"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1ada79799acab037af56")
}
> db.demo90.insertOne(
... {"words": ["sam", "adam"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1adb79799acab037af57")
}

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

> db.demo90.find();

這將生成以下輸出 -

{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }
{ "_id" : ObjectId("5e2c1adb79799acab037af57"), "words" : [ "sam", "adam" ] }

以下是查詢陣列中存在作為特定詞子串的字串的文件的查詢 -

> db.demo90.aggregate([ { $match: { $expr: { $anyElementTrue: { $map: { input: "$words", as: "j", in: { $ne: [ -1, { $indexOfBytes: [ "john", "$$j" ] } ] } } } } } } ]);

這將生成以下輸出 -

{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }

更新於:30-3-2020

679 次瀏覽

開啟您的 職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.