27

我想知道是否有办法只返回_id,user_idtotal没有items子文档。

{
    "_id" : 122,
    "user_id" : 123456,
    "total" : 100,
    "items" : [
            {
                    "item_name" : "my_item_one",
                    "price" : 20
            },
            {
                    "item_name" : "my_item_two",
                    "price" : 50
            },
            {
                    "item_name" : "my_item_three",
                    "price" : 30
            }
    ]
}
4

2 回答 2

34

The second parameter of find lets you select fields. So you can use this (note that the _id field is always selected anyway):

db.mycollection.find({}, {"user_id": 1, "total": 1});

You can also exclude certain fields, so this would be equivalent:

db.mycollection.find({}, {"items": 0});

You can exclude _id field by doing:

db.mycollection.find({}, {"user_id": 1, "_id": 0});
于 2012-06-14T04:11:48.717 回答
18

我正在寻找的是返回一个 id 列表,所以只返回 _id 但作为所有文档的数组。我是这样做的:

db. mycollection.distinct("_id", {})

第一个参数是您的 distict 字段,第二个是您的查询。更多关于不同的here。希望这可以帮助有类似要求的人。干杯!

于 2018-10-16T18:43:36.383 回答