如何使用 Java MongoDB 驅動程序檢索字段子集? (How to retrieve a subset of fields using the Java MongoDB driver?)


問題描述

如何使用 Java MongoDB 驅動程序檢索字段子集? (How to retrieve a subset of fields using the Java MongoDB driver?)

new poster here, I found this previous post but it's on C#, I tried doing this query straight into the java code of a JSP page, for some reason, it doesn't accept the info in the {} of the find() query and just gives out an error...

So peeps, how do I do this in Java:

// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});

Thanks!

PS: why the hell does C# have the nice little .Exclude() and .Include() commands and java doesn't? cries

‑‑‑‑‑

參考解法

方法 1:

The java driver follows the exact same API as the shell. Just pass a DBObject containing your field projection as the second argument to find or findOne  

As far as I know the official C# driver doesn't expose Include() and Exclude() methods as they violate the standard API. 

(by Gonçalo VieiraBrendan W. McAdams)

參考文件

  1. How to retrieve a subset of fields using the Java MongoDB driver? (CC BY‑SA 3.0/4.0)

#mongodb-java #java #mongoDB #JSP






相關問題

GridFS Java 對像是線程安全的嗎? (Are GridFS Java objects thread safe?)

Драйвер MongoDB Java: такога cmd: aggregate няма (MongoDB Java driver : no such cmd: aggregate)

Стварэнне парадкавага нумара ў mongoDB (Generating sequence number in mongoDB)

MongoDB java驅動如何判斷副本集是否處於自動故障轉移過程中? (How can MongoDB java driver determine if replica set is in the process of automatic failover?)

優化 mongodb 中的查詢 (Optimising queries in mongodb)

查詢數據時應該使用 MongoTemplate 還是 DBCollection (Should i use MongoTemplate or DBCollection when query data)

org.bson.codecs.configuration.CodecConfigurationException:找不到類 [Ljava.lang.String; 的編解碼器; (org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;)

如何使用 Java MongoDB 驅動程序檢索字段子集? (How to retrieve a subset of fields using the Java MongoDB driver?)

當使用 karras 和 clojure 給出字段時,如何更新 MongoDB 中的文檔? (How to update a Document in MongoDB when a field is given with karras & clojure?)

如何使用 java 代碼轉換 mongodb 查詢 (How to Transform mongodb query using java code)

MongoDB 文檔使用 Java 中的 findOneAndUpdate 方法更新數組元素 (MongoDB document update array element using findOneAndUpdate method in Java)

aws documentdb 是否為兩種方式的 ssl 驗證 mongodb 客戶端證書? (Does aws documentdb validate mongodb client certificate for two way ssl?)







留言討論