MongoDB:如何在Array Structured Collection中进行查询。

时间:2013-03-01 19:19:31

标签: mongodb

我有一个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());
        }

    }

}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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/