【问题标题】:writing mongoDB syntax编写 mongoDB 语法
【发布时间】:2016-06-30 06:59:55
【问题描述】:

大家好,如何将这个 mongoDB 语法写入 java

db.users.find( { user_id: /bc/ },{user_name:/bc/},{age:/2/} )

我的来源是

BasicDBObject sortOrder = new BasicDBObject();
MongoClient mongoClient;
DB db;

DBCollection table;
DBCursor cursor = null;

mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("stackoverflow");
boolean auth = db.authenticate("aku","kamu".toCharArray());
table = db.getCollection("questions");
cursor = table.find();

while (cursor.hasNext()) {
    DBObject object = cursor.next();
    out.print(object.get("title"));
    answer = rn.nextInt(8) + 0;
}

有什么解决方案吗? 我是使用 mongoDB 的新手

【问题讨论】:

  • 对不起,我的意思是如何在正则表达式上添加 or 子句我已经添加 cursor = table.find(new BasicDBObject("title", java.util.regex.Pattern.compile("milk") ));它成功了,但是如果我想添加更多像问题一样的正则表达式..谢谢之前:)
  • 分享你已经尝试过的东西

标签: java mongodb syntax


【解决方案1】:
    DBObject idMatch = new BasicDBObject("user_id","bc");
    DBObject usernameMatch = new BasicDBObject("user_name",bc);
    DBObject ageMatch = new BasicDBObject("age",2);

    DBObject andAll = new BasicDBObject("$and", Arrays.asList(existence, firstNotMatch, secondNotMatch));

    //calling  table.find will get you what you wanted.
    table.find(andAll);

如果您想对条件进行“或”运算,只需将 $and 替换为 $or。 请注意,上面的代码没有经过正确测试,您可能需要对其进行一些修改才能使其正常工作。

你的问题不清楚,但我希望我有所帮助。

【讨论】:

  • 如何打印resutl mate?
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 2017-11-08
  • 2012-11-17
  • 1970-01-01
  • 2019-02-22
相关资源
最近更新 更多