MongoDB 数据库,相当于 SELECT column1, column2 FROM tbl

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7206035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:12:59  来源:igfitidea点击:

MongoDB Database, equivalent for SELECT column1, column2 FROM tbl

selectmongodbrows

提问by Marc Stevens

From my MongoDB I want the equivalent for

从我的 MongoDB 中,我想要等效的

  SELECT column1, column2
  FROM tbl

With this code I get all the 'rows' but also all the 'columns'

使用此代码,我获得了所有“行”,但也获得了所有“列”

  DBCollection collection = database.getCollection("names");
  DBCursor cursor = collection.find();

I for example would like allthe 'rows' but onlythe 'columns': id, name, age

例如,我想要所有的“行”,但想要“列”:id、name、age

How would I do this?

我该怎么做?

Thanks for any help!!

谢谢你的帮助!!

回答by cjohn

db.collection.find({}, {_id: 1, name: 1, age: 1})

db.collection.find({}, {_id: 1, name: 1, age: 1})

The first argument to find (the predicate) is your selection criteria, e.g.

find(谓词)的第一个参数是您的选择标准,例如

db.collection.find({age: {$gte: 21}})

db.collection.find({年龄: {$gte: 21}})

The second limits the fields you retrieve, so for the names over everyone 21 or older:

第二个限制了您检索的字段,因此对于 21 岁或以上的所有人的姓名:

db.collection.find({age: {$gte: 21}}, {name: 1})

db.collection.find({age: {$gte: 21}}, {name: 1})

The field selector always pulls back _id unless you specifically turn it off:

除非您专门将其关闭,否则字段选择器始终会拉回 _id:

db.collection.find({}, {_id: 0})

db.collection.find({}, {_id: 0})

However, Mongo will not check for field existence by default. If you want to select certain fields, and match only results that have those fields, you will want to use:

但是,默认情况下 Mongo 不会检查字段是否存在。如果您想选择某些字段,并仅匹配具有这些字段的结果,您将需要使用:

db.collection.find({ age: { $exists: true } })

db.collection.find({ age: { $exists: true } })

The MongoDB website has a more detailed description of the .find() function!

MongoDB 网站对 .find() 函数有更详细的描述!

回答by Marc Stevens

Thanks!, I fixed it with the code below.

谢谢!,我用下面的代码修复了它。

    BasicDBObject select = new BasicDBObject();
    select.put("id", 1);
    select.put("name", 1);
    select.put("age", 1);
    collection.find(new BasicDBObject(), select);

Above code gives me all the records, with only the column names as above.

上面的代码给了我所有的记录,只有上面的列名。

回答by Vipin Pandey

If you want select one or multiple columns like SQL query. for example if your SQL query like this

如果您想选择一个或多个列,如 SQL 查询。例如,如果您的 SQL 查询是这样的

select name, content from knowledgebase where applicationId='2955f3e174dce55190a87ed0e133adwdeb92';

MongoDB query:

MongoDB查询:

db.knowledgebase.find({ "applicationId": "2955f3e174dce55190a87ed0e133adwdeb92"}, { "name": 1,    "content": 1});