配列要素に特定の値がないドキュメントのMongoDBクエリ
このような場合は、$elemMatchを使用してください。この演算子は、指定されたすべてのクエリ条件に一致する要素が少なくとも1つある配列フィールドを含むドキュメントに一致します。
ドキュメントを使用してコレクションを作成しましょう-
> db.demo239.insertOne(
... {
... "Name" : "Chris",
... "details" : [
... { "DueDate" : new ISODate("2019-01-21"), "ProductPrice" : 1270 },
... { "DueDate" : new ISODate("2020-02-12"), "ProductPrice" : 2000 }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441c6bf4cebbeaebec5157")
}
> db.demo239.insertOne(
... {
... "Name" : "David",
... "details" : [
... { "DueDate" : new ISODate("2018-11-11"), "ProductPrice" : 1450},
... { "DueDate" : new ISODate("2020-02-12") }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441c6cf4cebbeaebec5158")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo239.find();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e441c6bf4cebbeaebec5157"), "Name" : "Chris", "details" : [
{ "DueDate" : ISODate("2019-01-21T00:00:00Z"), "ProductPrice" : 1270 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z"), "ProductPrice" : 2000 }
]
}
{
"_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [
{ "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 },
{ "DueDate" : ISODate("2020-02-12T00:00:00Z") }
]
} 以下は、配列要素に特定の値がないドキュメントをフェッチするためのクエリです-
> db.demo239.find({ "details": { "$elemMatch": { "DueDate": { "$exists": true }, "ProductPrice": { "$exists": false } } } }) これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e441c6cf4cebbeaebec5158"), "Name" : "David", "details" : [ { "DueDate" : ISODate("2018-11-11T00:00:00Z"), "ProductPrice" : 1450 }, { "DueDate" : ISODate("2020-02-12T00:00:00Z") } ] } -
MongoDBを使用して、特定のネストされたドキュメントのオブジェクトの配列をクエリしますか?
ネストされたドキュメントのオブジェクトの配列をクエリするには、find()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo763.insertOne( ... { ... _id:1, ... CountryName:"US", ... "studentInformation": [ ... {
-
MongoDBで配列をクエリして、特定の値をフェッチします
配列から特定の値をフェッチするには、$ projectとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo761.insertOne( ... { ... "details": [ ... { ... "student": { ... &nb