我想在MongoDB中执行的查询如下
db.idx.update({"keyword":"Some dynamic keyword"},
{$addToSet:{url: "Some dynamic url"}},
{upsert: True})
我需要这个MongoDB查询的java等价物,我已经尝试了很多,但我一直在收到错误。我是Java和MongoDB的新手,但我渴望学习,所以,请帮助我!此外,如果您可以向我解释此查询的JSON及其结构。提前一百万谢谢:D(Y)
编辑: -
我尝试过: -
client = new MongoClient("localhost");
db = client.getDB("idx");
BasicDBObject lurl = new BasicDBObject();
BasicDBObject lurl2 = new BasicDBObject();
BasicDBObject lkey = new BasicDBObject();
for(Element e : links){
DBCollection colls = db.getCollection(e.text());
lurl.put("$addToSet", e.attr("href"));
lurl2.put("url", new BasicDBObject(lurl));
lkey.put("keyword", e.text());
colls.update(lkey, lurl2, true, false);
}
我收到的错误是: -
Exception in thread "main" java.lang.IllegalArgumentException: Document field names can't start with '$' (Bad Key: '$addToSet')
at com.mongodb.DBCollection.validateKey(DBCollection.java:1829)
at com.mongodb.DBCollection._checkKeys(DBCollection.java:1787)
at com.mongodb.DBCollection._checkValue(DBCollection.java:1810)
at com.mongodb.DBCollection._checkKeys(DBCollection.java:1788)
at com.mongodb.DBCollection._checkObject(DBCollection.java:1774)
at com.mongodb.DBCollectionImpl.update(DBCollectionImpl.java:250)
at com.mongodb.DBCollection.update(DBCollection.java:191)
at com.mongodb.DBCollection.update(DBCollection.java:224)
at myse.MySE.extractLinkData(MySE.java:55)
at myse.MySE.crawl(MySE.java:61)
at myse.MySE.main(MySE.java:69)
Java结果:1 建立成功(总时间:13秒)
答案 0 :(得分:1)
我认为您的更新参数错误(lurl2
):
lurl.put("url", e.attr("href"));
lurl2.put("$addToSet", new BasicDBObject(lurl));