有没有办法检查文档字段是否包含查询中的字符串?
例如:
collection cities
:
{ "_id" : 1, "name" : "Madrid" }
{ "_id" : 2, "name" : "Lisbon" }
{ "_id" : 3, "name" : "Paris" }
查询:
db.cities.find({
name: {$isIn: 'Address of the street, Lisbon'}
});
结果:
{ "_id" : 2, "name" : "Lisbon" }
答案 0 :(得分:3)
是的,这是可能的。看看$text
documentation。基本上你必须在字段上创建一个文本索引,然后你可以搜索如下:
SELECT
"menu_item_categories"."id", "menu_item_categories"."created_at",
"menu_item_categories"."updated_at", "menu_item_categories"."restaurant_id",
"menu_item_categories"."name", "menu_item_categories"."is_active",
COUNT("line_items"."order_id") AS "line_items_quantity",
(SELECT
U0."id", U0."created_at", U0."updated_at",
U0."restaurant_id", U0."category_id", U0."name",
SUM(U1."amount") AS "amount"
FROM "menu_items"
U0 INNER JOIN "line_items" U1
ON (U0."id" = U1."menu_item_id")
INNER JOIN "orders" U2
ON (U1."order_id" = U2."id")
WHERE (
U2."waiter_id" = 5 AND U2."closed_at"
BETWEEN 2017-12-20 14:19:16+00:00 AND 2017-12-26 14:19:16+00:00)
GROUP BY U0."id")
AS "menu_items",
SUM("line_items"."amount") AS "amount"
FROM "menu_item_categories"
LEFT OUTER JOIN "menu_items"
ON ("menu_item_categories"."id" = "menu_items"."category_id")
LEFT OUTER JOIN "line_items"
ON ("menu_items"."id" = "line_items"."menu_item_id")
GROUP BY "menu_item_categories"."id",
(
SELECT
U0."id", U0."created_at",
U0."updated_at", U0."restaurant_id",
U0."category_id", U0."name", SUM(U1."amount"
) AS "amount"
FROM "menu_items" U0
INNER JOIN "line_items" U1
ON (U0."id" = U1."menu_item_id")
INNER JOIN "orders" U2
ON (U1."order_id" = U2."id")
WHERE (U2."waiter_id" = 5
AND U2."closed_at"
BETWEEN 2017-12-20 14:19:16+00:00
AND 2017-12-26 14:19:16+00:00)
GROUP BY U0."id")
在这种情况下创建索引的示例。由于您的字段名为db.cities.find({ $text: { $search: "Address of the street, Lisbon" } })
:
name
您有很多可能性,例如排除短语,仅包含,区分大小写等。
让我们说我添加以下文件:
db.cities.createIndex( { name: "text" } )
如果我们这样搜索:
{ "_id" : NumberInt(1), "name" : "Madrid" }
{ "_id" : NumberInt(2), "name" : "Lisbon" }
{ "_id" : NumberInt(3), "name" : "Paris" }
{ "_id" : NumberInt(4), "name" : "Address"}
我们会得到2个结果:
db.cities.find({ $text: { $search: "Address of the street, Lisbon" } })
但如果我们这样搜索:
{ "_id" : NumberInt(2), "name" : "Lisbon"}
{ "_id" : NumberInt(4), "name" : "Address"}
我们只会得到:
db.cities.find({ $text: { $search: "-Address of the street, Lisbon" } })
因为( - )您可以排除包含此术语的文档。有关更多可能性,请查看文档
答案 1 :(得分:2)
db.cities.find({"name" : {$regex : ".*Lisbon.*"}});
是的,你可以使用正则表达式找到一些字符串模式。