0

如何在 mongo 中使用 in 获取第一个元素?如果我有一个类似的列表['car', 'house', 'cat', dog'],以及一个包含许多文档这些元素的集合,我想找到第一个包含 的文档cat,以及第一个包含dog等的文档。

我尝试过使用limit(),但实际上它只给了我一个文档,可以是car、 或dogcat等。

有没有办法将限制与 $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"
}
4

1 回答 1

2

您不能为 $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.

于 2013-07-04T11:16:21.753 回答