MongoDB get all values of 1 field

ε祈祈猫儿з 提交于 2021-01-29 17:18:48

问题


So I know that in mongodb, I can get all values and then iterate through them but I was wondering if in mongodb there is an option to get only a certain field.

So for example suppose my collection is structured as follows:

{_id:
    {
    field1,field2,field3}
    }
{description:
    {
    field1,field2,field3,
    data:{
    field1,field2,field3
    }
    }
    }
{otherdata:
{field1,field2,field3}
}

Now, I need the value of description.data.field1 so any suggestions on how to do that?

So far I have tried using following commands:

db.module.collection.description.data.find()
db.module.collection.description.find({'data':1})
db.module.collection.find('description.data.data':1})

But obviously, they did not work.

Any suggestions?


回答1:


First of all, the structure of your JSON isn't correct. The correct structure should be:

{
_id:{
    field1: "",
    field2: "",
    field3: ""
},
description:{
    field1: "",
    field2: "",
    field3: "",
    data:{
        field1: "",
        field2: "",
        field3: ""
    }
},
otherdata:{
    field1: "",
    field2: "",
    field3: ""
}
}

Now for what you need, you can use Projections

Something like this:

db.collection.find({}, {description.data.field1: 1})


来源:https://stackoverflow.com/questions/36460377/mongodb-get-all-values-of-1-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!