MongoDB एग्रीगेशन में $slice से ऐरे का विशिष्ट एलिमेंट निकालें
$slice ऑपरेटर एग्रीगेशन पाइपलाइन में ऐरे के सबसेट को निकालने के लिए उपयोग होता है। सिंटैक्स: $slice: [array, skip, limit]
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.exactPositionDemo.insertOne({"StudentName":"John","StudentScores":[78,98,56,45,89]});
{ "acknowledged": true, "insertedId": ObjectId("5cd29a1c345990cee87fd883") }
डॉक्यूमेंट देखें
> db.exactPositionDemo.find().pretty();
{
"_id": ObjectId("5cd29a1c345990cee87fd883"),
"StudentName": "John",
"StudentScores": [78, 98, 56, 45, 89]
}
केस 1: इंडेक्स 0 से 1 एलिमेंट लें (पहला एलिमेंट)
> db.exactPositionDemo.aggregate([
{ "$project": { "StudentScores": { "$slice": ["$StudentScores", 0, 1] } } }
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [78] }
केस 2: इंडेक्स 1 से 1 एलिमेंट लें (दूसरा एलिमेंट)
> db.exactPositionDemo.aggregate([
{ "$project": { "StudentScores": { "$slice": ["$StudentScores", 1, 1] } } }
]);
{ "_id": ObjectId("5cd29a1c345990cee87fd883"), "StudentScores": [98] }
$slice पैरामीटर समझें
- array: स्रोत ऐरे (
$StudentScores) - skip: छोड़ने वाले एलिमेंट की संख्या (0 = पहला, 1 = दूसरा, आदि)
- limit: वापस करने वाले एलिमेंट की संख्या
अन्य उपयोगी वेरिएशन
- अंतिम N एलिमेंट:
$slice: ["$array", -N] - शुरू से N एलिमेंट:
$slice: ["$array", N] - मध्य से:
$slice: ["$array", skip, limit]