MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Mongodb:Kueri objek json yang bersarang dalam array

Menggunakan operator Posisi

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

Keluaran

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

Menggunakan agregasi

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

keluaran

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

Menggunakan Driver Java

    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"));
    }

keluaran

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


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. mongodb periksa apakah titik dalam poligon

  2. Mongoose Mongodb menanyakan array objek

  3. Bagaimana mengembalikan hanya dokumen bersarang dari array dari semua dokumen

  4. Bagaimana cara mendapatkan dokumen tertanam tertentu di dalam koleksi MongoDB?

  5. MongoDB $sortByCount Operator Agregasi