MongoDB एग्रीगेशन में $match का उपयोग करके नेस्टेड ऐरे में स्ट्रिंग खोजना
MongoDB में नेस्टेड ऐरे के भीतर विशिष्ट स्ट्रिंग मान वाले दस्तावेज़ निकालने के लिए एग्रीगेशन पाइपलाइन में $match स्टेज का उपयोग करें।
उदाहरण: संग्रह और दस्तावेज़ बनाना
> db.demo424.insert(
{
"Information" : [
{ id:10, Name:"Chris" },
{ id:11, Name:"David" }
]
}
);
WriteResult({ "nInserted" : 1 })
> db.demo424.insert(
{
"Information" : [
{ id:101, Name:"Mike" },
{ id:102, Name:"John" }
]
}
);
WriteResult({ "nInserted" : 1 })
सभी दस्तावेज़ देखना
> db.demo424.find();
आउटपुट:
{ "_id" : ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information" : [ { "id" : 10, "Name" : "Chris" }, { "id" : 11, "Name" : "David" } ] }
{ "_id" : ObjectId("5e74eb9e15dc524f70227683"), "Information" : [ { "id" : 101, "Name" : "Mike" }, { "id" : 102, "Name" : "John" } ] }
"Chris" नाम वाले दस्तावेज़ निकालना
> db.demo424.aggregate(
[ { $match : { "Information.Name": "Chris" } } ]
);
आउटपुट:
{ "_id" : ObjectId("5e74eb9dbbc41e36cc3cae6a"), "Information" : [ { "id" : 10, "Name" : "Chris" }, { "id" : 11, "Name" : "David" } ] }
व्याख्या:
"Information.Name": "Chris"- डॉट नोटेशन से नेस्टेड ऐरे के ऑब्जेक्ट्स के Name फील्ड में खोज$match- पूरे दस्तावेज़ को फ़िल्टर करता है (ऐरे एलिमेंट नहीं)- मिलान करने वाला पूरा दस्तावेज़ लौटाया जाता है
केवल मिलान करने वाले ऐरे एलिमेंट्स के लिए:
db.demo424.aggregate([
{$unwind: "$Information"},
{$match: {"Information.Name": "Chris"}},
{$group: {_id: "$_id", Information: {$push: "$Information"}}}
])
सरल find() विकल्प:
db.demo424.find({"Information.Name": "Chris"})
यह समान परिणाम देता है और सरल है। एग्रीगेशन का उपयोग तब करें जब आगे ट्रांसफॉर्मेशन की आवश्यकता हो।
केस-इनसेंसिटिव खोज:
db.demo424.find({"Information.Name": {$regex: "chris", $options: "i"}})
// या एग्रीगेशन में
{$match: {"Information.Name": {$regex: "chris", $options: "i"}}}