【问题标题】:How to get specific data, but not a complete answer in mongodb/nodejs? [duplicate]如何获取特定数据,但不是 mongodb/nodejs 中的完整答案? [复制]
【发布时间】:2018-11-13 14:48:54
【问题描述】:

我有以下类型的集合

{
    "_id" : ObjectId("5bbb299f06229dddbaab553b"),
    "phone" : "+38 (031) 231-23-21",
    "date_call" : "2018-10-08",
    "adress_delivery" : "1",
    "quantity_concrete" : "1",
    "state" : "200",
    "comments" : "1",
    "is_order" : "n",
    "date_delivery" : "",
    "quantity_orders" : "",
    "summ_order" : "",
    "profit" : "",
    "id" : "0"
}

在终端请求时

db.getCollection("customers").find(
    {
        "$and" : [
            {
                "date_call" : {
                    "$lte" : "2018-10-10"
                }
            },
            {
                "date_call" : {
                    "$gte" : "2018-09-24"
                }
            }
        ]
    },
    {
        "phone" : 1,
        "is_order" : 1
    }
);

我得到了答案

{ 
  "_id" : ObjectId("5bbb299f06229dddbaab553b"),
  "phone" : "+38 (031) 231-23-21",
  "is_order" : "n"
}

当在 nodeJS 中请求相同的查询时

client.db(“mongoDB”).collection("customers").find(
    {
        "$and": [
            {
                "date_call": {
                    "$lte" : "2018-10-14"
                }
            },
            {
                "date_call": {
                    "$gte" : "2018-09-24"
                }
            }
        ]
    },
    {
        “phone”: 1,
        "is_order": 1
    }
)

我得到一个完整的答案,而不是查询中设置的“电话”和“is_order”。请告诉我如何才能只获取指定的数据?

【问题讨论】:

  • 通过 {fields:{"phone": 1, "is_order":1}} 作为投影对象

标签: node.js mongodb


【解决方案1】:

你可以这样使用project函数

client.db("mongoDB").collection("customers").find(
    {
        "$and": [
            {
                "date_call": {
                    "$lte" : "2018-10-14"
                }
            },
            {
                "date_call": {
                    "$gte" : "2018-09-24"
                }
            }
        ]
    })
    .project(
    {
        "phone": 1,
        "is_order": 1
    })
    .toArray((err, res) => {
        //your code here
    })

同样基于@Astro 注释传递{fields:{"phone": 1, "is_order":1}} 作为投影对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2013-09-26
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2020-03-06
    相关资源
    最近更新 更多