我有一个包含这样的对象的集合:
{
"_id": ObjectId("52ed12c144aecc4bf004d0b6"),
"title": "myBook",
"summary": "This is a book summary",
"chapters": [
{
"number": 1
"created_at": ISODate("2013-12-17T23:00:00Z")
},
{
"number": 2
"created_at": ISODate("2014-12-17T23:00:00Z")
}
]
"covers": [
"http://url.com/cover1.jpg",
"http://url.com/cover2.jpg",
],
"urls": [
"http://url.com/myBook",
"http://url.com/myBook/option2"
],
"genres": [
"comedy",
"romantic"
],
"created_at": ISODate("2012-12-17T23:00:00Z"),
"modify_at": ISODate("2014-02-01T15:41:48.149Z")
}
我只想获得'crated_at'> ='2012-12-17T23:00:00Z'的书籍,只有'created_at'>的章节“2013-12-17T23:00:00Z”。 (作为过滤器)
我的输出json应该是这样的:
{
"_id": ObjectId("52ed12c144aecc4bf004d0b6"),
"title": "myBook",
"summary": "This is a book summary",
"chapters": [
{
"number": 2
"created_at": ISODate("2014-12-17T23:00:00Z")
}
]
"covers": [
"http://url.com/cover1.jpg",
"http://url.com/cover2.jpg",
],
"urls": [
"http://url.com/myBook",
"http://url.com/myBook/option2"
],
"genres": [
"comedy",
"romantic"
],
"created_at": ISODate("2012-12-17T23:00:00Z"),
"modify_at": ISODate("2014-02-01T15:41:48.149Z")
}
在查询输出中可能是没有任何章节的书籍,其他的则包含所有章节的子集或书籍及其所有章节。
要按'created_at'搜索图书,请按以下方式查询:
db.books.find({ created_at: {$gte: ISODate("2012-12-17T23:00:00Z")} })
但我不知道我要添加什么来过滤此结果输出中的章节。
答案 0 :(得分:2)
您可以尝试使用聚合框架。
db.chapters.aggregate(
{ $match: { created_at: {$gte: ISODate("2012-12-17T23:00:00Z")} } },
{ $unwind: "$chapters" },
{ $match: { "chapters.created_at": {$gte: ISODate("2013-12-17T23:00:00Z")} } },
{ $group:
{
_id:
{
id: "$_id",
title: "$title",
summary: "$summary",
covers: "$covers",
urls: "$urls",
genres: "$genres",
created_at: "$created_at",
modify_at: "$modify_at"
},
chapters: { $push: "$chapters" }
}
},
{ $project:
{
_id: "$_id.id",
title: "$_id.title",
summary: "$_id.summary",
chapters: "$chapters",
covers: "$_id.covers",
urls: "$_id.urls",
genres: "$_id.genres",
created_at: "$_id.created_at",
modify_at: "$_id.modify_at"
}
}
)