使用mongodb中的$ in获取第一个文档

时间:2013-07-04 11:01:41

标签: mongodb

如何在mongo中获取第一个元素? 如果我有一个像['car', 'house', 'cat', dog']这样的列表,以及一个包含许多文档这些元素的集合,我想找到包含cat的第一个文档,首先包含dog

我尝试使用limit(),但实际上它只提供了一个文档,可以是cardogcat等。

有没有办法将限额与$ in结合使用?

由于

编辑: 我的数据示例:

{
    "_id": {
        "$oid": "51d53ace9e674607e837d62d"
    },
    "sensors": [{
        "name": "os-hostname",
        "value": "yahourt"
    }, {
        "name": "os-domain-name",
        "value": ""
    }, {
        "name": "os-platform",
        "value": "Win32NT"
    }, {
        "name": "os-fullname",
        "value": "Microsoft Windows XP Professional"
    }, {
        "name": "os-version",
        "value": "5.1.2600.131072"
    }],
    "type": "os",
    "serial": "2_os_os-hostname_yahourt"
} {
    "_id": {
        "$oid": "51d53ace9e674607e837d62e"
    },
    "sensors": [{
        "name": "cpu-id",
        "value": "_Total"
    }, {
        "name": "cpu-usage",
        "value": 37.2257042
    }],
    "type": "cpu",
    "serial": "2_cpu_cpu-id_total"
} {
    "_id": {
        "$oid": "51d53ace9e674607e837d62f"
    },
    "sensors": [{
        "name": "cpu-id",
        "value": "0"
    }, {
        "name": "cpu-usage",
        "value": 48.90282
    }],
    "type": "cpu",
    "serial": "2_cpu_cpu-id_0"
} {
    "_id": {
        "$oid": "51d53ace9e674607e837d630"
    },
    "sensors": [{
        "name": "cpu-id",
        "value": "1"
    }, {
        "name": "cpu-usage",
        "value": 25.54859
    }],
    "type": "cpu",
    "serial": "2_cpu_cpu-id_1"
} {
    "_id": {
        "$oid": "51d53ace9e674607e837d631"
    },
    "sensors": [{
        "name": "volume-name",
        "value": "C:"
    }, {
        "name": "volume-label",
        "value": ""
    }, {
        "name": "volume-total-size",
        "value": "52427898880"
    }, {
        "name": "volume-total-free-space",
        "value": "20305170432"
    }, {
        "name": "volume-percent-free-space",
        "value": "38"
    }, {
        "name": "volume-reads-per-second",
        "value": 0.0
    }, {
        "name": "volume-writes-per-second",
        "value": 9.324152
    }, {
        "name": "volume-read-bytes-per-second",
        "value": 0.0
    }, {
        "name": "volume-write-bytes-per-second",
        "value": 194141.6
    }, {
        "name": "volume-queue-length",
        "value": 0.0
    }],
    "type": "disk",
    "serial": "2_disk_volume-name_c"
}

1 个答案:

答案 0 :(得分:1)

您无法为$ in添加限制,但您可以使用聚合框架作弊:

db.collection.aggregate([
    {$match:{serial:{$in:[list_of_serials]}}},
    {$sort:{_id:-1}},
    {$group:{_id:'$serial',type:{$first:'$type'},sensors:{$first:'$sensors'},id:{$first:'$_id'}}}
]);

将获得每种类型的所有首次发现的列表。

修改

更新将根据_id

进行最后一次插入