MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBドキュメントから最初の配列要素を取得するための配列の投影


配列の最初の要素が必要な場合は、$gteとともに$sliceを使用できます。ドキュメントを使用してコレクションを作成しましょう-

> db.demo640.insertOne({Name:"John","Scores":[80,90,75]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c2eb86c954c74be91e6e0")
}
> db.demo640.insertOne({Name:"Chris","Scores":[85,70,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c2ece6c954c74be91e6e1")
}

find()メソッドを使用してコレクションからすべてのドキュメントを表示する-

> db.demo640.find();

これにより、次の出力が生成されます-

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80, 90, 75 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85, 70, 89 ] }

以下は、sing$slice-

を使用した配列の射影へのクエリです。
> db.demo640.find({Scores:{$gte:85}},{ "Scores": {$slice : 1}});

これにより、次の出力が生成されます-

{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85 ] }

  1. 配列の最初の要素を表示するC#プログラム

    以下は私たちの配列です- double[] myArr = {20.5, 35.6, 45.7, 55.6, 79.7}; 最初の要素を取得するには、First()メソッドを使用します。 myArr.AsQueryable().First(); 完全なコードを見てみましょう- 例 using System; using System.Linq; using System.Collections.Generic; class Demo {    static void Main() {       double[] myArr = {20.5

  2. 配列から最後の要素を取得するC#プログラム

    まず、配列を設定します- string[] str = new string[]{    "Java",    "HTML",    "jQuery",    "JavaScript",    "Bootstrap" }; 最後の要素の値を取得するには、長さを取得し、次の値を表示します- str[str.Length - 1] 上記は最後の要素を返します。 これが完全なコードです- 例 us