1

I have structure document like this :

// my structure
{
    "_id": ObjectId("5710e8d017487952a074027c"),
    "ID": "W1",
    "judul": "Candi Prambanan",
    "jenis": "Candi",
    "lokasi": [ 
        { "prov": "Yogyakarta" }, 
        { "kota": "Sleman" }
    ],
    "deskrip": "Candi Prambanan terletak di lingkungan Taman."
}

Now I try to use aggregate query of mongodb like this :

// query 1
db.wisata.aggregate([
    {"$unwind": "$lokasi"},
    {"$match": {
        "lokasi.kota": { "$exists": true, "$ne": null }
    }},
    {"$group": { _id: "$lokasi.kota"}}
])
//result
{
    "result": [ 
        {"_id": "Kampar" }, 
        {"_id": "Magelang"}, 
        {"_id": "Bantul"}, 
        {"_id": "Sleman"}
    ],
    "ok": 1
}

And I want use match to criteria like this:

//query 2
db.wisata.aggregate([
    {"$match": { 
       "lokasi.prov": "Yogyakarta"
    }},
    {"$group": {_id:"$lokasi.kota"}}
])
//result
{
    "result": [ 
        {"_id": ["Bantul"]}, 
        {"_id": ["Sleman"]}
    ],
    "ok": 1
}

The problem how I can use my criteria like query 2 but I get result like query 1, I have try like this :

//query 3
db.wisata.aggregate([
    {"$unwind": "$lokasi"},
    {"$match": { 
        "lokasi.prov": "Yogyakarta"
    }},
    {"$group": {_id:"$lokasi.kota"}}
])
//result
{
    "result" : [
        {"_id" : null}
    ],
    "ok" : 1
}

But result is null, please help me guys, thank you very much...

0

1 Answer 1

3

Try the following aggregate query:

db.wisata.aggregate([
    {"$match": {"lokasi.prov": "Yogyakarta"}}, 
    {"$group": {"_id": "$lokasi.kota"}},
    {"$unwind": "$_id"}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.