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

Kueri kecocokan agregat Mongodb dengan prioritas pada kecocokan penuh

Mengingat contoh Anda yang tepat, ini dapat dicapai dengan cara berikut - jika skenario dunia nyata Anda sedikit lebih rumit, Anda mungkin akan menemui masalah:

db.accounts.aggregate([{
    $match: {
        "username": /pat/i // find all documents that somehow match "pat" in a case-insensitive fashion
    }
}, {
    $addFields: {
        "exact": { 
            $eq: [ "$username", "pat" ] // add a field that indicates if a document matches exactly
        },
        "startswith": { 
            $eq: [ { $substr: [ "$username", 0, 3 ] }, "pat" ] // add a field that indicates if a document matches at the start
        }

    }
}, {
    $sort: {
        "exact": -1, // sort by our primary temporary field
        "startswith": -1 // sort by our seconday temporary
    }
}, {
    $project: {
        "exact": 0, // get rid of the "exact" field,
        "startswith": 0 // same for "startswith"
    }
}])

Cara lain adalah menggunakan $facet yang mungkin terbukti sedikit lebih kuat dengan mengaktifkan skenario yang lebih kompleks tetapi lebih lambat (beberapa orang di sini akan membenci saya, untuk proposal ini):

db.accounts.aggregate([{
    $facet: { // run two pipelines against all documents
        "exact": [{ // this one will capture all exact matches
            $match: {
                "username": "pat"
            }
        }],
        "others": [{ // this one will capture all others
            $match: {
                "username": { $ne: "pat", $regex: /pat/i }
            }
        }]
    }
}, {
    $project: {
        "result": { // merge the two arrays
            $concatArrays: [ "$exact", "$others" ]
        }
    }
}, {
    $unwind: "$result" // flatten the resulting array into separate documents
}, {
    $replaceRoot: { // restore the original document structure
        "newRoot": "$result"
    }
}])



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Gunakan LINQ di C# untuk menemukan catatan MondoDB ketika nilai dalam bidang daftar cocok dengan nilai kriteria dari daftar

  2. Terapkan pemetaan tipe dengan mgo

  3. Strategi untuk Agregasi Real-Time di MongoDB

  4. TypeError:db.collection bukan fungsi, TIDAK BISA MENDAPATKAN

  5. Mongo Query gagal dengan kode kesalahan 13 dan pesan kesalahan 'tidak diotorisasi'