PyMongo Atlas Search 不返回任何内容

PyMongo Atlas Search not returning anything

我正在尝试使用 Atlas 为 MongoDB 进行全文搜索。我通过 Python 中的 PyMongo 驱动程序执行此操作。我正在使用聚合管道,并进行了 $search,但似乎 return 什么都没有。

cursor = db.collection.aggregate([
    {"$search": {"text": {"query": "hello", "path": "text_here"}}},
    {"$project": {"file_name": 1}}
])

for x in cursor:
    print(x)

我试图用这段代码实现的是搜索集合中名为“text_here”的字段,我正在搜索术语“hello”和 return搜索所有包含该术语的结果并按“file_name”列出它们。但是,它 return 什么都没有,我很困惑,因为这与文档网站上的示例代码几乎相同。我现在唯一能想到的是可能路径不正确,它无法访问我指定的字段。此外,此代码 return 没有错误,只是 return 什么都没有,因为我通过遍历游标进行了测试。

如果你只是做一个查找和项目,你不需要聚合查询,只需要一个find()。您想要的语法是:

db.collection.find({'$text': {'$search': 'hello'}}, {'file_name': 1})

等价于使用聚合:

cursor = db.collection.aggregate([
    {'$match': {'$text': {'$search': 'hello'}}},
    {'$project': {'file_name': 1}}])

工作示例:

from pymongo import MongoClient, TEXT

db = MongoClient()['mydatabase']

db.collection.create_index([('text_here', TEXT)])
db.collection.insert_one({"text_here": "hello, is it me you're looking for", "file_name": "foo.bar"})

cursor = db.collection.find({'$text': {'$search': 'hello'}}, {'file_name': 1})

for item in cursor:
    print(item)

打印:

{'_id': ObjectId('5fc81ce9a4a46710459de610'), 'file_name': 'foo.bar'}

我遇到了同样的问题。我通过在查询中传递索引名称来解决它。例如:

{ 
  index: "name_of_the_index",
  text: {
    query: 'john doe',
    path: 'name'
  }
}

我按照教程进行操作,但在不指定“索引”名称的情况下无法返回任何结果。我希望在文档中提到这是强制性的。