mongodb按多个数组项查找 [英] mongodb find by multiple array items

查看:48
本文介绍了mongodb按多个数组项查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的记录;

{
  "text": "text goes here",
  "words": ["text", "goes", "here"]
}

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

How can I match multiple words from it in MongoDB? When matching a single word I can do this;

db.find({ words: "text" })

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

But when I try this for multiple words, it doesn't work;

db.find({ words: ["text", "here"] })

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

I'm guessing that by using an array, it tries to match the entire array against the one in the record, rather than matching the individual contents.

推荐答案

取决于您是否要查找 words 包含两个元素(texthere) 使用 $all:

Depends on whether you're trying to find documents where words contains both elements (text and here) using $all:

db.things.find({ words: { $all: ["text", "here"] }});

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

or either of them (text or here) using $in:

db.things.find({ words: { $in: ["text", "here"] }});

这篇关于mongodb按多个数组项查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆