【问题标题】:How to show specific column in mongo db collection如何在 mongodb 集合中显示特定列
【发布时间】:2019-11-15 21:20:17
【问题描述】:

我试图在 mongodb 集合中显示特定的列。但它不起作用。如何显示特定的列。

user_collection

[{
"user_name":"hari",  
"user_password":"123456"
}]

find_query

db.use_collection.find({},{projection:{user_name:1}})

我得到了输出

[{
"user_name":"hari",  
"user_password":"123456"
}]

异常输出

[{
"user_name":"hari",  
}]

【问题讨论】:

    标签: mongodb mongodb-query mongoid


    【解决方案1】:

    试试:

    db.use_collection.find({}, {user_name:1, _id: 0 })
    

    这样你就得到了user_name字段并排除了_id

    额外信息: project fieldsproject fields excluding the id

    有聚合:

    db.use_collection.aggregate( [ { $project : { _id: 0, user_name : 1 } } ] )
    

    【讨论】:

    • 我试过了,但它显示了整个记录@Alejandro Montilla
    • 奇怪,你能用aggregate吗??
    【解决方案2】:

    试试:

    db.use_collection.find({}, {user_password:0, _id: 0 ,user_name:1  })
    

    【讨论】:

    • 请在您的答案中添加一些解释,以便其他人可以从中学习
    【解决方案3】:

    你可以试试这个

    Mongo 查询:

    db.users.aggregate([
        {
            "$project":
            {
                "_id": 0,
                "first_name": 1,
            }
        }
    ])
    

    或者在红宝石中(Mongoid)

    User.collection.aggregate(
      [
        "$project":
        {
            "_id": 0,
            "first_name": 1,
        }
      ]
    )
    

    如果您尝试检查记录,可以先将其转换为数组(例如User.collection.aggregate(...).to_a

    在 Mongoid 中编写时可以使用官方的 mongodb reference,通常只需要在左侧的属性名称上使用双引号即可使其在 Mongoid 上运行。

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 2018-09-16
      • 1970-01-01
      • 2021-05-10
      • 2020-04-01
      • 1970-01-01
      • 2012-08-14
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多