由于您的收藏有 100m 大,请尝试对字段进行索引,并$text
在收藏上进行搜索
创建文本索引
https://docs.mongodb.com/manual/core/index-text/
$text
搜索
https://docs.mongodb.com/manual/reference/operator/query/text/index.html
> db.books.ensureIndex({"$**" : "text"})
指数
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 2,
"note" : "all indexes already exist",
"ok" : 1
}
结果
>
> db.books.find({$text : {$search : "ch2"}})
{ "_id" : 2, "chapters" : { "0" : { "title" : "ch4" }, "1" : { "title" : "ch2" }, "2" : { "title" : "ch5" } }, "description" : "book two" }
{ "_id" : 1, "chapters" : { "0" : { "title" : "ch1" }, "1" : { "title" : "ch2" }, "2" : { "title" : "ch3" } }, "description" : "book one" }
>
这在没有文本索引的情况下是可能的,通过将章节转换$objectToArray
为搜索并返回$arrayToObject
,但这将对 100m 文档执行此操作,不适合您的情况
db.books.aggregate(
[
{$project : { description : 1, arr : {$objectToArray : "$$ROOT.chapters"}}},
{$match : {"arr.v.title" : "ch2"}},
{$project : { description : 1 , chapters : { $arrayToObject : "$$ROOT.arr"}}}
]
).pretty()
结果
> db.books.aggregate([{$project : { description : 1, arr : {$objectToArray : "$$ROOT.chapters"}}}, {$match : {"arr.v.title" : "ch2"}}, {$project : { description : 1 , chapters : { $arrayToObject : "$$ROOT.arr"}}}])
{ "_id" : 1, "description" : "book one", "chapters" : { "0" : { "title" : "ch1" }, "1" : { "title" : "ch2" }, "2" : { "title" : "ch3" } } }
{ "_id" : 2, "description" : "book two", "chapters" : { "0" : { "title" : "ch4" }, "1" : { "title" : "ch2" }, "2" : { "title" : "ch5" } } }
>