MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb:Fragt ein JSON-Objekt ab, das in einem Array verschachtelt ist

Positionsoperator verwenden

db.test.find(
    { "array.value": "value2" },
    { "array.$": 1, _id : 0 }
)

Ausgabe

{ "array" : [ { "name" : "test2", "value" : "value2" } ] }

Aggregation verwenden

db.test.aggregate([
    { $unwind : "$array"},
    { $match : {"array.value" : "value2"}},
    { $project : { _id : 0, array : 1}}
])

Ausgabe

{ "array" : { "name" : "test2", "value" : "value2" } }

Java-Treiber verwenden

    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    DB db = mongoClient.getDB("mydb");
    DBCollection collection = db.getCollection("test");

    DBObject unwind = new BasicDBObject("$unwind", "$array");
    DBObject match = new BasicDBObject("$match", new BasicDBObject(
            "array.value", "value2"));
    DBObject project = new BasicDBObject("$project", new BasicDBObject(
            "_id", 0).append("array", 1));

    List<DBObject> pipeline = Arrays.asList(unwind, match, project);
    AggregationOutput output = collection.aggregate(pipeline);

    Iterable<DBObject> results = output.results();

    for (DBObject result : results) {
        System.out.println(result.get("array"));
    }

Ausgabe

{ "name" : "test2" , "value" : "value2"}