简体   繁体   中英

how to get specific fields from MongoDB Atlas in java?

Following Java code return the JSON object which contains all fields of "users" collection in my MongoDB Atlas database, but I want only one field value, say "password". What should I do?

package com.servlets;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoException;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
public class mongoDB 
{
    public static void main(String[] args)
    {
        String username = "gary29198";
        Gson gson = new Gson();
        MongoClientURI uri = new MongoClientURI("mongodb+srv://gary29198:0001221149@sih2019-yp3zc.mongodb.net/test?retryWrites=true");
        MongoClient mongoClient = new MongoClient(uri);
        MongoDatabase database = mongoClient.getDatabase("SIH2019");
        MongoCollection<Document> collections = database.getCollection("users");
        FindIterable<Document> find = collections.find(Filters.eq("username", username));
        try( MongoCursor<Document> cursor = find.iterator() ) 
        {
            while(cursor.hasNext())
            {
                System.out.println(gson.toJson(cursor.next()));
            }
        }
        catch(MongoException e)
        {
            System.out.println(e.getMessage());
        }
    }

}

see this example:

package com.jcg.java.mongodb;
import org.apache.log4j.Logger;
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongoDemo {

    private static Logger log = Logger.getLogger(MongoDemo.class);

    // Fetching all documents from the mongo collection.
    private static void getAllDocuments(MongoCollection<Document> col) {
        log.info("Fetching all documents from the collection");

        // Performing a read operation on the collection.
        FindIterable<Document> fi = col.find();
        MongoCursor<Document> cursor = fi.iterator();
        try {
            while(cursor.hasNext()) {
                log.info(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }

    // Fetch a selective document from the mongo collection.
    private static void getSelectiveDocument(MongoCollection<Document> col) {
        log.info("Fetching a particular document from the collection");

        // Performing a read operation on the collection.
        String col_name = "name", srch_string = "Charlotte Neil";
        FindIterable<Document> fi = col.find(Filters.eq(col_name, srch_string));        
        MongoCursor<Document> cursor = fi.iterator();
        try {
            while(cursor.hasNext()) {
                log.info(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }

    @SuppressWarnings("resource")
    public static void main(String[] args) {

        // Mongodb initialization parameters.
        int port_no = 27017;
        String host_name = "localhost", db_name = "sampledb", db_coll_name = "emp";

        // Mongodb connection string.
        String client_url = "mongodb://" + host_name + ":" + port_no + "/" + db_name;
        MongoClientURI uri = new MongoClientURI(client_url);

        // Connecting to the mongodb server using the given client uri.
        MongoClient mongo_client = new MongoClient(uri);

        // Fetching the database from the mongodb.
        MongoDatabase db = mongo_client.getDatabase(db_name);

        // Fetching the collection from the mongodb.
        MongoCollection<Document> coll = db.getCollection(db_coll_name);

        // Fetching all the documents from the mongodb.
        getAllDocuments(coll);

        log.info("\n");

        // Fetching a single document from the mongodb based on a search_string.
        getSelectiveDocument(coll);
    }
}

Can use projections

collection.find().projection(Projections.include("password"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM