MongoDB数据库,相当于SELECT列1,列2 FROM tbl [英] MongoDB Database, equivalent for SELECT column1, column2 FROM tbl
问题描述
在我的MongoDB中,我希望得到与之对应的
From my MongoDB I want the equivalent for
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();
例如,
我想要全部行",但仅列":ID,名称,年龄
I for example would like all the 'rows' but only the 'columns': id, name, age
我该怎么做?
感谢您的帮助!
推荐答案
db.collection.find({},{_id:1,名称:1,年龄:1})
db.collection.find({}, {_id: 1, name: 1, age: 1})
要查找(谓词)的第一个参数是您的选择条件,例如
The first argument to find (the predicate) is your selection criteria, e.g.
db.collection.find({age:{$ gte:21}})
db.collection.find({age: {$gte: 21}})
第二个字符限制了您检索的字段,因此对于21岁或21岁以上的所有人来说都是这样:
The second limits the fields you retrieve, so for the names over everyone 21 or older:
db.collection.find({age:{$ gte:21}},{name:1})
db.collection.find({age: {$gte: 21}}, {name: 1})
除非您专门将其关闭,否则字段选择器始终拉回_id:
The field selector always pulls back _id unless you specifically turn it off:
db.collection.find({},{_id:0})
db.collection.find({}, {_id: 0})
但是,默认情况下,Mongo不会检查字段是否存在.如果要选择某些字段,并且仅匹配具有这些字段的结果,则将要使用:
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:
db.collection.find({age:{$ exists:true}})
db.collection.find({ age: { $exists: true } })
MongoDB网站对.find()函数有更详细的描述!
The MongoDB website has a more detailed description of the .find() function!
这篇关于MongoDB数据库,相当于SELECT列1,列2 FROM tbl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!