0

我有一个 Mongo DB COllection,如图所示

{
    "name": "SAM",
    "collection": [
        {
            "date": "2013-03-16",
            "values": [
                {
                    "price": "24.0"
                }
            ]
        },
        {
            "date": "2013-04-20",
            "values": [
                {
                    "price": "10.0"
                }
            ]
        },
        {
            "date": "2013-05-18",
            "values": [
                {
                    "price": "12.0"
                }
            ]
        },
        {
            "date": "2013-06-22",
            "values": [
                {
                    "price": "10.0"
                }
            ]
        },
        {
            "date": "2013-09-21",
            "values": [
                {
                    "price": "38.0"
                }
            ]
        }
    ]
}

我试图获取与特定日期(2013-03-16)相关的数据,如图所示,但我正在获取所有日期的数据。

这就是我尝试过的。

请告诉我我在哪里做错了。

package com;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

public class Test {

    public static void main(String args[]) throws UnknownHostException {
        Mongo mongo = new Mongo();
        DB db = mongo.getDB("test");
        DBCollection mycollection = db.getCollection("mycollection");

        BasicDBObject query = new BasicDBObject();
        query.put("name", "SAM");
        query.put("collection.date", "2013-03-16");

        DBCursor cursor = mycollection.find(query);

        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

    }

}
4

2 回答 2

1

您可以$在 的字段选择参数中使用位置投影运算符来执行此操作find

BasicDBObject query = new BasicDBObject();
query.put("name", "SAM");
query.put("collection.date", "2013-03-16");
BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);
fields.put("collection.$", 1);

DBCursor cursor = mycollection.find(query, fields);
于 2013-03-01T19:52:33.707 回答
0

您正在尝试查询数组集合中的元素,您需要使用 $elemMatch,而不是,

query.put("collection.date", "2013-03-16");

你可以试试

query.put("collection", new BasicDBObject("$elemMatch", new BasicDBObject("date","2013-03-16")));

在此处阅读更多信息:http: //docs.mongodb.org/manual/reference/projection/elemMatch/

于 2013-03-01T19:45:33.193 回答