我正在尝试设计一个基于包含元数据数组的文档的查询。
书 = { 标题:字符串, 元数据:[字符串]
为了找到想要的书,我有另一个包含多个元数据术语的搜索字符串数组。数组的长度可以根据存在的元数据搜索词的数量而变化。如何查询以仅查找包含所有指定元数据搜索词的书籍?
例子:
book1 - 自然、树木、昆虫、雾、音乐 book2 - 音乐、艺术、运动
使用 [music, sports] 的元数据进行搜索会得到 book2。
我怎样才能最有效地设计这个查询?我可以这样做并避免嵌套查询吗?任何帮助将不胜感激。
最佳答案
您可以使用 $all
运算符来完成此操作。
来自文档:
If, instead, you wish to find an array that contains both the elements "red" and "blank", without regard to order or other elements in the array, use the $all operator:
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
关于Mongodb查询可变数量的搜索词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919259/