MongoDB प्रोजेक्शन में पोजीशनल $ ऑपरेटर से ऐरे का मैचिंग एलिमेंट लौटाएं
क्वेरी कंडीशन से मैच करने वाले ऐरे एलिमेंट को ही प्रोजेक्शन में शामिल करने के लिए पोजीशनल $ ऑपरेटर उपयोग करें।
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.getASpecificObjectDemo.insertOne({
_id: 1,
"CustomerName": "Larry",
"CustomerDetails": {
"CustomerPurchaseDescription": [
{id: 100, "ProductName": "Product-1", "Amount": 10000},
{id: 101, "ProductName": "Product-2", "Amount": 10500},
{id: 102, "ProductName": "Product-3", "Amount": 10200}
]
}
});
{ "acknowledged": true, "insertedId": 1 }
डॉक्यूमेंट देखें
> db.getASpecificObjectDemo.find().pretty();
{
"_id": 1,
"CustomerName": "Larry",
"CustomerDetails": {
"CustomerPurchaseDescription": [
{"id": 100, "ProductName": "Product-1", "Amount": 10000},
{"id": 101, "ProductName": "Product-2", "Amount": 10500},
{"id": 102, "ProductName": "Product-3", "Amount": 10200}
]
}
}
id = 101 वाला परचेज विवरण प्राप्त करें
> db.getASpecificObjectDemo.find(
{_id: 1, "CustomerDetails.CustomerPurchaseDescription.id": 101},
{_id: 0, "CustomerDetails.CustomerPurchaseDescription.$": 1}
);
{ "CustomerDetails": { "CustomerPurchaseDescription": [{"id": 101, "ProductName": "Product-2", "Amount": 10500}] } }
कैसे काम करता है
- क्वेरी:
_id: 1और ऐरे मेंid: 101वाला एलिमेंट - प्रोजेक्शन:
"CustomerDetails.CustomerPurchaseDescription.$": 1 $- क्वेरी से मैच करने वाला पहला ऐरे इंडेक्स को रिप्रेजेंट करता है- केवल वही एलिमेंट परिणाम में शामिल होता है
सीमाएं
- केवल पहला मैचिंग एलिमेंट लौटाता है
- एक ही प्रोजेक्शन में एकाधिक पोजीशनल $ नहीं उपयोग कर सकते
- नेस्टेड ऐरे के लिए काम नहीं करता (केवल एक लेवल)
नेस्टेड ऐरे के लिए: $elemMatch प्रोजेक्शन
db.collection.find(
{_id: 1},
{nestedArray: {$elemMatch: {id: 101}}}
)