MongoDB Database, equivalent for SELECT column1, column2 FROM tbl

狂风中的少年 提交于 2019-12-04 15:55:27

问题


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();

I for example would like all the 'rows' but only the 'columns': id, name, age

How would I do this?

Thanks for any help!!


回答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}})

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

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

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

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:

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

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




回答2:


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.




回答3:


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

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

MongoDB query:

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


来源:https://stackoverflow.com/questions/7206035/mongodb-database-equivalent-for-select-column1-column2-from-tbl

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