kongshem
kongshem

Reputation: 332

MongoDB: Combine two .find() statements

Using Java. I have two .find() queries that I want to combine and get a Document containing the results of both queries. I have managed to create them individually like this. Notice that the queries are on two different top-level fields. The last statement below is a query on the same field with two conditions.

FindIterable<Document> iterable = db.getCollection("1dag").find(new Document("id", "10"));

and

FindIterable<Document> iterable2 = db.getCollection("1dag").find(
                new Document().append("timestamp", new Document()
                        .append("$gte",startTime)
                        .append("$lte",endTime)));

I can't find any documentation on this. Is this where I should use the "$and" or "$where" statements?

EDIT is this the way to do it?

FindIterable<Document> iterable7 = db.getCollection("1dag").find(
                new Document()
                        .append("timestamp", new Document()
                                .append("$gte", startTime)
                                .append("$lte", endTime))
                        .append("id", new Document()
                                .append("$eq", 10)));

Upvotes: 0

Views: 1486

Answers (2)

Dev
Dev

Reputation: 13753

Your query will work perfectly.

The query db.inventory.find({id:{$eq:10}}) is equivalent to db.inventory.find({id: 10})

So simplifying your query:

FindIterable<Document> iterable7 = db.getCollection("1dag").find(
            new Document().append("timestamp", new Document()
                            .append("$gte", startTime)
                            .append("$lte", endTime))
                    .append("id",10));

Upvotes: 1

chridam
chridam

Reputation: 103365

To create the equivalent Java query for the following mongo shell query

db.getCollection("1dag").find({
    "id": "10",
    "timestamp": {
        "$gte": 1412204098,
        "$lte": 1412204099
    }
})

you should specify a logical conjunction (AND) for multiple query conditions by appending conditions to the query document:

FindIterable<Document> iterable = db.getCollection("1dag").find(
        new Document("id", "10")
            .append("timestamp", 
                new Document("$gte", 1412204098)
                     .append("$lte", 1412204099)
            )
    );

Upvotes: 1

Related Questions