我正在尝试从mongodb中检索文档,并根据条件(deleted != null
)从数组中删除一些对象。以下是我要定位的项目的简化示例:
{
"_id" : ObjectId("54ec9cac83a214491d2110f4"),
"name" : "my_images",
"images" : [
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2311026b0cb289ed04188"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:20:16.961Z"),
},
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2314a26b0cb289ed04189"),
"deleted" : ISODate("2015-02-24T15:38:14.826Z"),
"date_added" : ISODate("2015-02-28T21:21:14.910Z"),
},
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2315526b0cb289ed0418a"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:21:25.042Z"),
},
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2315d26b0cb289ed0418b"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:21:33.081Z"),
}
]
}
成功的查询将返回相同的但是删除了一个图像对象,因为它具有ISODate而不是null。像这样:
{
"_id" : ObjectId("54ec9cac83a214491d2110f4"),
"name" : "my_images",
"images" : [
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2311026b0cb289ed04188"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:20:16.961Z"),
},
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2315526b0cb289ed0418a"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:21:25.042Z"),
},
{
"ext" : "jpeg",
"type" : "image/jpeg",
"_id" : ObjectId("54f2315d26b0cb289ed0418b"),
"deleted" : null,
"date_added" : ISODate("2015-02-28T21:21:33.081Z"),
}
]
}
我尝试使用聚合到$unwind
图像然后$match
只显示相关图像,但我现在需要重新创建文档,否则它将返回剩余的3个“展开”文档。
这是我到目前为止的地方:
Collection.aggregate([
{ $match:
{ _id: ObjectID(collection_id) }
},
{ $unwind: "$images" },
{ $match:
{ "images.deleted": null }
}
// Next step in the pipeline to
// reconfigure into one document
// goes here
], function (err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
});
有没有办法从完全错误的方式创建一个剩余的或正在进行的文档?
感谢。
答案 0 :(得分:0)
正如您所提到的,您需要将展开的,已过滤的文档重新分组为原始形状。您可以使用$group
:
Collection.aggregate([
{ $match:
{ _id: ObjectID(collection_id) }
},
{ $unwind: "$images" },
{ $match:
{ "images.deleted": null }
},
// Regroup the docs by _id to reassemble the images array
{$group: {
_id: '$_id',
name: {$first: '$name'},
images: {$push: '$images'}
}}
], function (err, result) {
if (err) {
console.log(err);
return;
}
console.log(result);
});