MongoDBのサブドキュメントでサブドキュメントをフィルタリングしますか?
これには、$ unwindと一緒にaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo583.insert([
... {
... "details1" : [
... {
... "details2" : [
... {
... "isMarried" : true,
... "Name" : "Chris"
... },
... {
... "isMarried" : true,
... "Name" : "Bob"
... }
... ]
... },
... {
... "details2" : [
... {
... "isMarried" : false,
... "Name" : "Chris"
... },
... {
... "isMarried" : true,
... "Name" : "Mike"
... }
... ]
... }
... ]
... }
... ]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
}) find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo583.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [
{ "details2" : [
{ "isMarried" : true, "Name" : "Chris" },
{ "isMarried" : true, "Name" : "Bob" }
] },
{ "details2" : [
{ "isMarried" : false, "Name" : "Chris" },
{ "isMarried" : true, "Name" : "Mike" }
] }
] } 以下は、サブドキュメントをサブドキュメントでフィルタリングするためのクエリです-
> var q= [
... {
... "$match": {
... "details1.details2.isMarried": true,
... "details1.details2.Name": "Chris"
... }
... },
... {
... "$unwind": "$details1"
... },
... {
... "$unwind": "$details1.details2"
... },
... {
... "$match": {
... "details1.details2.isMarried": true,
... "details1.details2.Name": "Chris"
... }
... }
... ];
> db.demo583.aggregate(q).pretty(); これにより、次の出力が生成されます-
{
"_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"),
"details1" : {
"details2" : {
"isMarried" : true,
"Name" : "Chris"
}
}
} -
MongoDBを使用して埋め込みドキュメントの配列でクエリをフィルタリングしますか?
これには、MongoDBでaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo736.insertOne( ... { ... "_id": "101", ... "details1": [ ... { ... &q
-
MongoDBドキュメントから特定の値をフィルタリングする
特定の値をフィルタリングするには、MongoDBで$filterを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo751.insertOne( ... { ... _id: 101, ... details: [ ... { Name: "Robert", id:110,Age:21}, ... &nb