MongoDB Java:使用QueryBuilder $ in运算符在Mongo中查找对象不会返回任何内容 [英] MongoDB Java: Finding objects in Mongo using QueryBuilder $in operator returns nothing

查看:110
本文介绍了MongoDB Java:使用QueryBuilder $ in运算符在Mongo中查找对象不会返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为MongoRule

I have a JUnit rule called as MongoRule looks like

public class MongoRule extends ExternalResource {

    private static final Logger LOGGER = LoggerFactory.getLogger(MongoRule.class);
    private final MongoService mongoService;

    public MongoRule() throws UnknownHostException {
        mongoService = new MongoService(getConfiguredHost(), getConfiguredPort(), getConfiguredDatabase());
    }

    @Override
    protected void before() throws Throwable {
        LOGGER.info(" Setting up Mongo Database - " + getConfiguredDatabase());
    }

    @Override
    protected void after() {
        LOGGER.info("Shutting down the Mongo Database - " + getConfiguredDatabase());
        mongoService.getMongo().dropDatabase(getConfiguredDatabase());
    }

    @Nonnull
    public DB getDatabase() {
        return mongoService.getMongo().getDB(getConfiguredDatabase());
    }

    @Nonnull
    public Mongo getMongo() {
        return mongoService.getMongo();
    }

    @Nonnull
    public MongoService getMongoService() {
        return mongoService;
    }

    public static int getConfiguredPort() {
        return Integer.parseInt(System.getProperty("com.db.port", "27017"));
    }

    @Nonnull
    public static String getConfiguredDatabase() {
        return System.getProperty("com.db.database", "database");
    }

    @Nonnull
    public static String getConfiguredHost() {
        return System.getProperty("com.db.host", "127.0.0.1");
    }
}

然后我尝试插入一些文档,如下所示

Then I try to insert some documents as following

 public static void saveInDatabase() {
        LOGGER.info("preparing database - saving some documents");
        mongoRule.getMongoService().putDocument(document1);
        mongoRule.getMongoService().putDocument(document2);
    }

其中document1document2是有效的DBObject文档.架构看起来像

Where document1 and document2 are valid DBObject documents. The schema looks like

{
    Id: 001
    date_created: 2012-10-31
    vars: {
      '1': {
           name: n1
           value:v1
       }
      '2': {
           name: n2
           value:v2
       }
      '3': {
           name: n3
           value:v3
       }

} 
{
    Id: 002
    date_created: 2012-10-30
    vars: {
      '1': {
           name: n4
           value:v4
       }
      '2': {
           name: n5
           value:v5
       }
      '3': {
           name: n6
           value:v6
       }

}

现在我尝试查询集合并获取这些对象,所以我这样做

Now I try to query the collection and get these objects, so I do this

public static void getDocuments(List<String> documentIds) {
        BasicDBList docIds = new BasicDBList();
        for (String docId: documentIds) {
            docIds.add(new BasicDBObject().put("Id", docId));
        }
        DBObject query = new BasicDBObject();
        query.put("$in", docIds);
        DBCursor dbCursor = mongoRule.getDatabase().getCollection("mycollection").find(query);
        System.out.println(dbCursor == null);
        if (dbCursor != null) {
            while (dbCursor.hasNext()) {
                System.out.println("object -  " + dbCursor.next());
            }
        }
    }  

mycollection是持久保存所有文档的集合,它来自外部服务.
当我运行此文档时,我会看到以下

mycollection is the collection where all documents are persisted, this comes from an external service.
When I run this document I see following

preparing database - saving some documents
inserting document - DBProposal # document1
inserting document - DBProposal # document2
false

这意味着collection.find()找不到这些文档.

Which means collection.find() could not find these documents.

我不在这里做什么?如何退回文件?

What is that I am not doing right here? How can I get the documents back?

我对将JavaMongo结合使用非常陌生,并使用了参考来构建查询

I am very new to using Java with Mongo and used this reference to construct the query

更新
更改查询的构造方式后,我仍然看不到文档

UPDATE
After changing the way query is constructed, I still don't see documents

public static void getDocuments(List<String> documentIds) {
            BasicDBList docIds = new BasicDBList();
            docIds.addAll(documentIds)
            DBObject query = new BasicDBObject();
            query.put("$in", docIds);
            DBCursor dbCursor = mongoRule.getDatabase().getCollection("mycollection").find(query);
            System.out.println(dbCursor == null);
            if (dbCursor != null) {
                while (dbCursor.hasNext()) {
                    System.out.println("object -  " + dbCursor.next());
                }
            }
        } 

,并且通过以下方式返回集合名称:

and the collection Name is returned via

private static String getCollectionName(@Nonnull final DBObject dbObject) {
        return "mycollection";
    }

推荐答案

您现在所做的等效于:

db.col.find({$in:[{Id:id1}, {Id:id2}, ..., {Id:idN}]})

这不是有效的查询,因为您没有指定要在$ in上输入的字段.我假设您想要

Which is not a valid query since you're not specifying what field to $in on. I'm assuming you want :

db.col.find({Id:{$in:[id1, id2, ..., idN]}})

相应地更改查询构造代码,就可以了.

Change your query construction code accordingly and you should be fine.

添加正确的代码:

public static void getDocuments(List<Integer> documentIds) {

            BasicDBList docIds = new BasicDBList();
            docIds.addAll(documentIds)
            DBObject inClause = new BasicDBObject("$in", docIds);
            DBObject query = new BasicDBObject("Id", inClause);
            DBCursor dbCursor = mongoRule.getDatabase().getCollection("mycollection").find(query);
            System.out.println(dbCursor == null);
            if (dbCursor != null) {
                while (dbCursor.hasNext()) {
                    System.out.println("object -  " + dbCursor.next());
                }
            }
        } 

请注意,这假定"Id"不是"_id"

Please note that this assumes "Id" is something other than "_id"

这篇关于MongoDB Java:使用QueryBuilder $ in运算符在Mongo中查找对象不会返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆