gpt4 book ai didi

java - 如何在java中从MongoDB Atlas获取特定字段?

转载 作者:行者123 更新时间:2023-12-02 10:24:32 25 4
gpt4 key购买 nike

以下 Java 代码返回 JSON 对象,其中包含 MongoDB Atlas 数据库中“users”集合的所有字段,但我只想要一个字段值,例如“password”。我该怎么办?

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

}

最佳答案

可以使用投影

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

关于java - 如何在java中从MongoDB Atlas获取特定字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com