簡體   English   中英

如何在使用mongoDb java異步驅動程序插入mongoDb集合后獲取_id

[英]How to get _id after insertion to mongoDb collection using mongoDb java asynchronous driver

如何在使用mongoDb java異步驅動程序插入mongoDb集合后獲取_id

package test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoClientConfiguration;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.bson.builder.BuilderFactory;
import com.allanbank.mongodb.bson.builder.DocumentBuilder;
import com.allanbank.mongodb.builder.Aggregate;
import com.xxxx.dto.FeedMongoDTO;

/**
* @author abhi
* 
*/
public class MongoTestService {

public static transient Log log = LogFactory.getLog(FeedMongoOperations.class);

private MongoClient mongo;
private MongoDatabase db;
private MongoCollection collection;

public boolean openDbConnection() {
    try {
        MongoClientConfiguration config = new MongoClientConfiguration();
        config.addServer("localhost:27017");
        config.setMaxConnectionCount(10);

        mongo = MongoFactory.createClient(config);

        db = mongo.getDatabase("feedDatabase");

        return true;
    } catch (Exception e) {
        return false;
    }
}

public boolean closeDbConnection() {
    try {
        mongo.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

public String save(FeedMongoDTO feed, String collectionName) {
    try {

        collection = db.getCollection(collectionName);
        DocumentBuilder b = BuilderFactory.start();
        Document d1 = b.add("url", feed.getUrl()).addLong("mongoTimeStamp", feed.getMongoTimestamp())
                .add("feedJsonArray", feed.getFeedJsonArray()).build();

        collection.insert(d1);

        return d1.get("id").toString();
    } catch (Exception ex) {
        return null;
    }
}

public FeedMongoDTO getFeed(String mongoId, String collectionName) {

    FeedMongoDTO feedMongoDTO = null;

    try {
        return feedMongoDTO;
    } catch (Exception ex) {
        return null;
    }
}
}

其中FeedMongoDTO的結構如下所示

public class FeedMongoDTO {

    private String id;
    private String url;
    private Long mongoTimeStamp;
    private JSONArray feedJsonArray;

    //  Getters 
    public String getId() {
        return id;
    }

    public String getUrl() {
        return url;
    }

    public Long getMongoTimestamp() {
        return mongoTimeStamp;
    }

    public JSONArray getFeedJsonArray() {
        return feedJsonArray;
    }


    //  Setters 
    public void setId(String id) {
        this.id = id;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setMongoTimestamp(Long mongoTimestamp) {
        this.mongoTimeStamp = mongoTimestamp;
    }

    public void setFeedJsonArray(JSONArray feedJsonArray) {
        this.feedJsonArray = feedJsonArray;
    }

}

我需要獲取_id的值,但這里d1.get("id").toString()導致NullPointerException

還有一件事我很困惑,我是否正確地執行了Save()方法。 使用通常的mongodb驅動程序非常容易。

public String save(FeedMongoDTO feed, String collectionName) {
    try {
        mongoTemplate.save(feed, collectionName);
        return feed.getId();
    } catch (Exception ex) {
        return null;
    } 
} 

提前致謝

阿比拉什:)

如果這是你需要經常做的事情,為什么不自己設置_id。 您可以使用0-arg構造函數輕松構造新的ObjectId ,並在插入之前將其添加到文檔中。

ObjectId id = new ObjectId();
documentBuilder.add("_id", id);
collection.insert(documentBuilder);

看起來愚蠢運行單獨的查詢只是為了檢索id。

在我看來,異步java驅動程序提供了進行同步查詢的方法,例如使用正常的findOne調用。 這對您的需求有意義嗎?

我在使用我的異步節點應用程序在我的目錄中創建一個新名稱時遇到了這個問題。 我想通過它的ID將用戶帶到新創建的Name,而不會將用戶扔回目錄列表。 allTwentyQuestions得到了這樣的權利,雖然不太適合Node,並引導我走上這條道路:

addName: function(nameDB, newName, callback){
  nameID = new require('mongodb').ObjectID();
  nameDB.collection('nameList').insert({"_id" : nameID, 'Name' : newName, 'type' : '', 'active' : 'no', 'modifiedDate' : ''}, function(err, result) {
    if (!err) {
        // success
        callback(null, nameID);
    } else {
        // error
        callback('error', err);
    }
  });
}

然后我會從我的應用程序中調用該函數:

mongo.addName(nameDB, newName, function(err, result) {
  if (!err){
    // success
    // direct the user to the proper page with this new ObjectID found in the var 'result'
  } else {
    // error
    console.log('There was an error adding the name: '+ result);
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM