Node.js 使用mongodb查找数组中的元素
我只想根据查询计算数组中的元素。我尝试了以下命令,但没有解决我的问题 我想在DATA2数组上计算时间戳介于“2017-02-17T18:30:00.000Z”和“2017-02-18T18:29:59.999Z”之间的元素,但它只返回1 执行的代码: 代码1Node.js 使用mongodb查找数组中的元素,node.js,mongodb,mongodb-query,aggregation-framework,mongojs,Node.js,Mongodb,Mongodb Query,Aggregation Framework,Mongojs,我只想根据查询计算数组中的元素。我尝试了以下命令,但没有解决我的问题 我想在DATA2数组上计算时间戳介于“2017-02-17T18:30:00.000Z”和“2017-02-18T18:29:59.999Z”之间的元素,但它只返回1 执行的代码: 代码1 db.ABC.aggregate([{ $match: { $and: [{ DATA2: {
db.ABC.aggregate([{
$match: {
$and: [{
DATA2: {
$exists: true
}
}, {
"DATA2.TimeStamp": {
$gte: require('../../modules/getDates').getFromDate(item),
$lte: require('../../modules/getDates').getToDate(item)
}
}, {
Client_id: "123" /*req.query.client_id*/
}]
}
}, {
$project: {
DATASiz: {
$size: "$DATA2"
},
"has bananas": {
$in: ["DATA2.$.TimeStamp"]
}
}
}], function(err, result) {
console.log(result)
callBack();
})
代码2
db.abc.find({ $and:[{DATA2: {$exists: true}},{Client_id: "123"},{"DATA2": { $elemMatch: { TimeStamp: { $gte: require('../../modules/getDates').getFromDate(item), $lte: require('../../modules/getDates').getToDate(item) } } }}]
}, function(err, result) {
console.log(JSON.stringify(result))
callBack();
})
代码3
//db.abc.find //also tried
db.abc.count({
$and: [{
DATA2: {
$exists: true
}
}, {
"DATA2.TimeStamp": {
$gte: require('../../modules/getDates').getFromDate(item),
$lte: require('../../modules/getDates').getToDate(item)
}
}, {
Client_id: "123" /*req.query.client_id*/
}]
},{
"DATA2.$":1
}, function(err, result) {
console.log(result)
callBack();
})
JSON格式:
{
"_id": {
"$oid": "57c7404985737e2c78fde6b3"
},
"ABC": "1304258470",
"Status": "Not Found",
"DATA1": [
{123},{123},{123}
],
"Remark": "Not Found",
"DATA2": [
{
"TimeStamp": "2017-02-18T09:01:43.060Z",
"NdrStatus": "Door Locked",
},
{
"TimeStamp": "2017-02-18T08:09:43.347Z",
"NdrStatus": "HOLD",
},
{
"TimeStamp": "2017-02-20T08:09:43.347Z",
"NdrStatus": "HOLD",
}
]
}
结果:
我使用代码3获取DATA2的第一个元素,但我知道根据查询,2个元素将返回
我估计有两个。
还使用了$unwind$修订
提前感谢。您可以使用和运算符来实现此目的:
var start = require('../../modules/getDates').getFromDate(item),
end = require('../../modules/getDates').getToDate(item);
db.ABC.aggregate([
{
"$match": {
"DATA2": { "$exists": true },
"DATA2.TimeStamp": { "$gte": start, "$lte": end },
"Client_id": "123"
}
},
{
"$project": {
"DATASiz": {
"$size": {
"$filter": {
"input": "$DATA2",
"as": "item",
"cond": {
"$and": [
{ "$gte": ["$$item.TimeStamp", start] },
{ "$lte": ["$$item.TimeStamp", end] }
]
}
}
}
}
}
}
], function(err, result) {
console.log(result);
callBack();
});
您的MongoDB服务器版本是什么?mongod版本:3.2.11非常感谢。您节省了我的时间。:)我忘了尝试$filter:(再次感谢您。