mongodb通过多个数组项找到

Ste*_*ger 91 arrays search mongodb

如果我有这样的记录;

{
  "text": "text goes here",
  "words": ["text", "goes", "here"]
}
Run Code Online (Sandbox Code Playgroud)

如何在MongoDB中匹配多个单词?匹配单个单词时,我可以这样做;

db.find({ words: "text" })
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试多个单词时,它不起作用;

db.find({ words: ["text", "here"] })
Run Code Online (Sandbox Code Playgroud)

我猜测通过使用数组,它会尝试将整个数组与记录中的数组进行匹配,而不是匹配单个内容.

小智 153

取决于您是否尝试使用以下方法查找words包含两个元素(texthere)的文档$all:

db.things.find({ words: { $all: ["text", "here"] }});
Run Code Online (Sandbox Code Playgroud)

或其中任何一个(texthere)使用$in:

db.things.find({ words: { $in: ["text", "here"] }});
Run Code Online (Sandbox Code Playgroud)

  • 这对我也有帮助,我需要它来查找数组中的对象ID,并且在$ in:[ObjectId("4f9f2c336b810d0cf0000017")]之类的地方失败,$ in:["4f9f2c336b810d0cf0000017"]工作了 (3认同)
  • 这比循环数组并执行单个 find() 更好吗? (2认同)