[英]Mongodb Java - How to return all fields of a collection
使用驅動Java Mongodb,我正在尋找一種返回一個集合的所有字段的方法。例如,我有一個集合“people”,如何獲取所有字段,我想要輸出: 'id','name', '城市'...
非常感謝,我終於得到了答案。
DBCursor cur = db.getCollection("people").find();
DBObject dbo = cur.next();
Set<String> s = dbo.keySet();
從手冊:
要返回集合中的所有文檔,請在沒有條件文檔的情況下調用find
方法。 例如,以下操作會查詢 restaurant 集合中的所有文檔。
FindIterable<Document> iterable = db.getCollection("restaurants").find();
迭代結果並將塊應用於每個結果文檔。
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
您需要決定對您有意義的樣本數量,但這會提取最后 10 個提交。
Document nat = new Document().append("$natural",-1);
FindIterable<Document> theLastDocumentSubmitted = collection.find().limit(10).sort(nat);
ArrayList<String>fieldkeys = new ArrayList<String>();
for (Document doc : theLastDocumentSubmitted) {
Set<String> keys = doc.keySet();
Iterator iterator = keys.iterator();
while(iterator.hasNext()){
String key = (String) iterator.next();
String value = (String) doc.get(key).toString();
if(!fieldkeys.contains(key)) {
fieldkeys.add(key);
}
}
}
System.out.println("fieldkeys" + fieldkeys.toString());
下面的代碼將返回給定集合中的所有字段。
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collection_name"); AggregateIterable<Document> output = mongoCollection.aggregate(Arrays.asList( new Document("$project", Document("arrayofkeyvalue", new Document("$objectToArray", "$$ROOT"))), new Document("$unwind", "$arrayofkeyvalue"), new Document("$group", new Document("_id", null).append("allkeys", new Document("$addToSet", "$arrayofkeyvalue.k"))) ));
下面的代碼將返回人員集合的所有字段:
db.people.find()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.