我有一个像bellow的文件:
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请告诉我! 感谢
答案 0 :(得分:0)
由于你的收藏量很大,所以请尝试索引字段,然后$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
,但这样做可以用于100米文档,不适合您的情况
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" } } }
>