use*_*646 5 date mongoose mongodb aggregation-framework
在一个集合中,我存储了这种文档
{
"_id" : 1,
"created_at" : "2016/01/01 12:10:10",
...
}.
{
"_id" : 2,
"created_at" : "2016/01/04 12:10:10",
...
}
Run Code Online (Sandbox Code Playgroud)
我想通过使用聚合管道找到文件"creared_at"> 2016/01/01.
任何人都有解决方案将"created_at"转换为日期,因此可以进行聚合吗?
正如您所提到的,您需要首先更改模式,以便该created_at字段保存日期对象而不是字符串,就像当前情况一样,然后您可以使用find()方法或聚合框架查询集合.前者是最简单的方法.
要转换created_at为日期字段,您需要find()使用该forEach()方法迭代方法返回的游标,在循环中将created_at字段转换为Date对象,然后使用$set运算符更新字段.
利用批量API进行批量更新,提供更好的性能,因为您将以1000个批量发送操作到服务器,这样可以提供更好的性能,因为您不会向服务器发送每个请求,只需每次一次1000个请求.
以下演示了此方法,第一个示例使用MongoDB版本中提供的Bulk API >= 2.6 and < 3.2.它通过将created_at字段更改为日期字段来更新集合中的所有文档:
var bulk = db.collection.initializeUnorderedBulkOp(),
counter = 0;
db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "created_at": newDate}
});
counter++;
if (counter % 1000 == 0) {
bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
bulk = db.collection.initializeUnorderedBulkOp();
}
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }
Run Code Online (Sandbox Code Playgroud)
下一个示例适用于新的MongoDB版本3.2,该版本已弃用Bulk API并使用以下方法提供了一组较新的api bulkWrite():
var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}),
bulkOps = [];
cursor.forEach(function (doc) {
var newDate = new Date(doc.created_at);
bulkOps.push(
{
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "created_at": newDate } }
}
}
);
if (bulkOps.length === 1000) {
db.collection.bulkWrite(bulkOps);
bulkOps = [];
}
});
if (bulkOps.length > 0) { db.collection.bulkWrite(bulkOps); }
Run Code Online (Sandbox Code Playgroud)
架构修改完成后,您可以在集合中查询日期:
var dt = new Date("2016/01/01");
db.collection.find({ "created_at": { "$gt": dt } });
Run Code Online (Sandbox Code Playgroud)
如果您希望使用聚合框架进行查询,请运行以下管道以获得所需的结果.它使用$match运算符,类似于find()方法:
var dt = new Date("2016/01/01");
db.collection.aggregate([
{
"$match": { "created_at": { "$gt": dt } }
}
])
Run Code Online (Sandbox Code Playgroud)
以上所有答案都可以使用cursors,但是mongodb始终建议使用aggregation管道。随着新$dateFromString的mongodb 3.6,它非常简单。
https://docs.mongodb.com/manual/reference/operator/aggregation/dateFromString/
db.collection.aggregate([
{$project:{ created_at:{$dateFromString:{dateString:'$created_at'}}}}
])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14334 次 |
| 最近记录: |