Mongo:根据条件计算数组中元素的总数

时间:2013-11-18 09:46:19

标签: mongodb mongodb-query aggregation-framework

我是mongoDB的新手。我已经知道mongoDb的一些基本查询但没有进展。 我的文档如下:

{
    "_id" : ObjectId("5289deaa84aedcc100228259"),
    "gender" : "male",
    "intrest" : [
        {
            "userId" : ObjectId("5286294984ae18ac5d19af36"),
            "timestamp" : ISODate("2013-11-18T09:32:38.040Z"),
            "status" : "Pending"
        },
        {
            "userId" : ObjectId("5286295984ae18ac5d19af37"),
            "timestamp" : ISODate("2013-11-18T09:33:17.493Z"),
            "status" : "Pending"
        }
    ],
    "intrestAccepted" : [ ],
    "intrestCancled" : [ ],
    "intrestDeclined" : [ ],
    "intrestReceived" : [
        ObjectId("5286294984ae18ac5d19af36"),
        ObjectId("5286295984ae18ac5d19af37")
    ],
    "owner" : ObjectId("5286293284ae18ac5d19af35"),
    "postDesc" : "gggg",
    "tags" : [
        "ggg"
    ]
}
{

    "_id" : ObjectId("5289dea084aedcc100228258"),
    "gender" : "female",
    "intrest" : [
        {
            "userId" : ObjectId("5286294984ae18ac5d19af36"),
            "timestamp" : ISODate("2013-11-18T09:32:42.934Z"),
            "status" : "Pending"
        },
        {
            "userId" : ObjectId("5286295984ae18ac5d19af37"),
            "timestamp" : ISODate("2013-11-18T09:33:18.520Z"),
            "status" : "Pending"
        }
    ],
    "intrestAccepted" : [ ],
    "intrestCancled" : [ ],
    "intrestDeclined" : [ ],
    "intrestReceived" : [
        ObjectId("5286294984ae18ac5d19af36"),
        ObjectId("5286295984ae18ac5d19af37")
    ],
    "owner" : ObjectId("5286293284ae18ac5d19af35"),
    "postDesc" : "asdf",
    "tags" : [
        "asdf"
    ]
}
{

    "_id" : ObjectId("5289dec984aedcc10022825a"),
    "gender" : "male",
    "intrest" : [
        {
            "userId" : ObjectId("5286295984ae18ac5d19af37"),
            "timestamp" : ISODate("2013-11-18T09:33:20.996Z"),
            "status" : "Pending"
        }
    ],
    "intrestAccepted" : [ ],
    "intrestCancled" : [ ],
    "intrestDeclined" : [ ],
    "intrestReceived" : [
        ObjectId("5286295984ae18ac5d19af37")
    ],
    "owner" : ObjectId("5286294984ae18ac5d19af36"),
    "postDesc" : "fff",
    "tags" : [
        "fff"
    ]
}

我想查找其所有者为ObjectId("5286293284ae18ac5d19af35")

的intrestReceived []的总计数

我应该写什么查询。请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以尝试这样简单的事情:

intrestReceived_length = 0
db.col.find({ _id: ObjectId("5286293284ae18ac5d19af35") }).forEach( function( doc ){
  intrestReceived_length = doc.intrestReceived.length;
});

查找将仅提取与您提供的ObjectId匹配的文档,然后我们在游标上使用forEach来迭代所有(一个)结果。在forEach回调中,我们只使用JavaScript array.length命令来提取数组的大小。

您还可以通过在find命令中提供投影来仅输出intrestReceived数组:

db.col.find({ _id: ObjectId("5286293284ae18ac5d19af35") }, { "intrestReceived": 1 })...

这将返回相同的文档,但它只包含_idintrestReceived属性。