【问题标题】:How to fetch _id field only in array using mongoDB in sailsJs如何在sailsJs中使用mongoDB仅在数组中获取_id字段
【发布时间】:2018-10-12 06:04:55
【问题描述】:

我在从mongoDB 中检索sailsJs 中的数据时遇到问题。我想要一个 _id 字段的纯数组,但它返回一个 JSON 对象数组,类似于

[
      {_id: 'sdfdsr3434redf'},
      {_id: '6sdgydewu7fr3'}, 
      ...
]

但我只想要 ID 列表,例如:

['sdfdsr3434redf', '6sdgydewu7fr3', ...]

代码如下:

  let userIDList = await col.find({
                        $or: [
                            {permission: 'student'},
                            {permission: 'staff'}
                        ]
                },{ select : ['_id'] }).toArray();

我尝试了一种方法,效果如下(@atishay_jain),

let userIDList = await col.find({
                 $or: [
                      {permission: 'student'},
                      {permission: 'staff'}
                 ]},{ select : ['_id'] }).toArray();

let final = userIDList.map((v, i) => { return v._id });
console.log(final);

但我需要一些捷径来让它更相关。在此先感谢:)

【问题讨论】:

  • 你在使用猫鼬 ODM 吗?
  • 不,我用的是 mongodb。看。 const { MongoClient, ObjectID } = require('mongodb');
  • 没关系,看看答案。

标签: node.js mongodb mongoose sails.js


【解决方案1】:

如果您想在javascript 中进行操作。这是代码。

let userIDList = await col.find({
                 $or: [
                      {permission: 'student'},
                      {permission: 'staff'}
                 ]},{ select : ['_id'] }).toArray();

let final = userIDList.map((v, i) => { return v._id });
console.log(final);

【讨论】:

    【解决方案2】:

    获取所有文档后,需要遍历它们并解析值。

    由于数据库查询提供 { key: value },因此您必须获取 key 的值。

    试试这个,

        let userIDList = [];
    
        await col.find({
            $or: [
                { permission: 'student' },
                { permission: 'staff' }
            ]
        },{ select : ['_id'] }).toArray().forEach(function(obj) { 
            userIDList.push(obj._id) 
        });
        console.log(userIDList);
    

    【讨论】:

      【解决方案3】:

      如果您想在一个命令中执行此操作,可以尝试“distinct”命令。

      col.distinct("_id", {
          $or: [{permission: 'student'}, {permission: 'staff'}]
      })
      

      【讨论】:

        【解决方案4】:

        您只能获得如下所示的 _id 列

        let userIDList = await col.find({
                                $or: [
                                    {permission: 'student'},
                                    {permission: 'staff'}
                                ]
                        },{_id:1}).toArray();
        

        【讨论】:

          猜你喜欢
          • 2020-08-22
          • 2018-05-15
          • 1970-01-01
          • 1970-01-01
          • 2020-04-20
          • 1970-01-01
          • 1970-01-01
          • 2014-05-27
          • 1970-01-01
          相关资源
          最近更新 更多