在文档中查找数组并按年和月过滤

时间:2016-11-13 21:31:59

标签: node.js mongodb mongoose mongoose-schema

我使用nodejs和mongoose。我有这样的架构:

var comptesSchema = new Schema ({
name: String,
solde: Number,
user_id: Number,
operations: [{
    name: String,
    amount: Number,
    debit: Boolean,
    mensuel: Boolean,
    date: Date,
    category: String
}]

});

和我的数据:

[{
"_id": "5826d10b829c732cacd92f6f",
"name": "compte courant",
"__v": 0,
"solde": -40,
"operations": [
  {
    "date": "2016-11-12T23:00:00.000Z",
    "debit": false,
    "amount": 10,
    "name": "tivoli",
    "_id": "5828b1bf42ae876e287525dc"
  },
  {
    "date": "2016-11-12T23:00:00.000Z",
    "debit": false,
    "amount": 20,
    "name": "st georges",
    "_id": "5828d1e1c951b07888e79c61"
  },
  {
    "date": "2016-11-11T23:00:00.000Z",
    "debit": false,
    "amount": 10,
    "name": "oiufdsouifd",
    "_id": "5828d51e679a4a7718a55b48"
  }
]}]

我想找到操作数组中的元素,并按年和月过滤。

你知道吗?谢谢:))

2 个答案:

答案 0 :(得分:0)

我们假设您为monthyear设置了过滤器选项,如下所示:

var month = 11;
var year = 2016;

试试这个:

comptesSchema.find({'operations.date': {
    "$gte": new Date(year, month, 1),
    "$lt": new Date(year, month, 0)
  }, function (err, comptes) {
    // Get you filtered comptes
});

答案 1 :(得分:0)

我有2个操作:一个在11月,一个在12月。

我试试这个:

    .get('/compte/:compteId/operation/date', function(req, res) {
    var compteId = req.params.compteId;
    var month = 11;
    var year = 2016;
    Comptes.find({
        'operations.date': {
            "$gte": new Date(year, month, 1),
            "$lt": new Date(year, month, 0)
        }
    }, function(err, compte) {
        res.json(compte);
    });
})

但它没有用,我有这个:

[{
"_id": "5826d10b829c732cacd92f6f",
"name": "compte courant",
"__v": 0,
"solde": -70,
"operations": [
  {
    "date": "2016-11-13T23:00:00.000Z",
    "debit": false,
    "amount": 10,
    "name": "test",
    "_id": "58297e475c208d081c810aec"
  },
  {
    "date": "2016-12-13T23:00:00.000Z",
    "debit": false,
    "amount": 20,
    "name": "fsdf",
    "_id": "58297e655c208d081c810aed"
  }
]}]

它将在十一月和十二月返回日期..我不明白:(