我有一个帖子有这个属性:
Ingredients: ['onions', 'carrots']
我发现这篇帖子$in
添加了其中一种成分。
但我需要找到'洋葱'或/和'胡萝卜'。如果我寻找'洋葱'和/或'胡萝卜',它就不起作用。
我怎么能这样做?
答案 0 :(得分:2)
如果要检查数组中是否存在两个值,请使用$all运算符:
{ Ingredients: { $all: ['onions', 'carrots'] }}
如果要使用$in运算符检查任何值:
{ Ingredients: { $in: ['onions', 'carrots'] }}
答案 1 :(得分:0)
您最好的选择是在“成分”字段上创建文本索引。请参阅MongoDB文档中的text index。您可以创建索引(假设您的集合名称为Trigger
),以简洁起见。
collection
创建索引后,搜索集合为
db.collection.createIndex({Ingredients:'text'})
你应该得到带有微小变化的结果,比如
db.collection.find({$text:{$search:'onion'}})
答案 2 :(得分:0)
你正在寻找多个"%喜欢%"结果在这里。因此,将搜索模式放入正则表达式数组中 - 然后可以将其用于$ all / $ in查询。
即: -
var checkList = ["onion","carrot"];
var regexArray = [];
for (var i = 0; i < checkList.length; i++) {
regexArray[i] = new RegExp(checkList[i],"i");
}
db.collection.find({Ingredients:{$in:regexArray}})
如果在php中运行,则转换为: -
$checkList = ["onion","carrot"];
$regexArray = [];
for ($i = 0; $i < sizeof($checkList); $i++){
$regexArray[$i] = new MongoRegex('/'.$checkList[$i].'/i');
}
$query = array('ingredients'=>array('$in'=>$regexArray));
答案 3 :(得分:0)
这将以“胡萝卜”和“洋葱”作为成分返回帖子:
流星方式:
db.getCollection('food').find({ingredients:{$and: [
{ingredients: {
$regex: `.*onion.*`,
$options : 'i'
}},
{ingredients: {
$regex: `.*carrot.*`,
$options : 'i'
}}
]}})
MongoDB的:
{$and:[{ingredients:/^onion/}, {ingredients:/^carrot/}]}