0

我有如下文件:

books: [
{_id: 1,chapters:{0:{title:'ch1'},1:{title:'ch2'},2:{title:'ch3'}},description:'book one'},
{_id: 2,chapters:{0:{title:'ch4'},1:{title:'ch2'},2:{title:'ch5'}},description:'book two'},
{_id: 3,chapters:{0:{title:'ch6'},1:{title:'ch7'},2:{title:'ch8'}},description:'book three'},
{_id: 4,chapters:{0:{title:'ch9'},1:{title:'ch10'},2:{title:'ch11'}},description:'book four'}
]

所以我的问题是:我如何在这个集合中找到标题为“ch2”的章节的对象?我不能改变它的数据和结构!

也许这是一个帮助:我使用来自jenssegers/laravel-mongodb 的嵌入式文档。如果有更好的库可以在 laravel 中使用 mongodb,请告诉我!谢谢

4

1 回答 1

0

由于您的收藏有 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" } } }
> 
于 2018-01-20T12:07:38.950 回答