ドキュメントから配列要素を削除するMongoDBクエリ?
次の構文に示すように、$pullを使用してMongoDBドキュメントから配列要素を削除します-
db.yourCollectionName.update( { },{ $pull: { yourFieldName: yourValue }},{multi:true }); まず、ドキュメントを使用してコレクションを作成しましょう-
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd90d011a844af18acdffc1")
}
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd90d2e1a844af18acdffc2")
} 以下は、find()メソッドを使用してコレクションからすべてのドキュメントを表示するためのクエリです-
> db.removeArrayElementsDemo.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName" : [
"John",
"Sam",
"Carol",
"David"
]
}
{
"_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName" : [
"Chris",
"Robert",
"John",
"Mike"
]
} ドキュメントから配列要素を削除するクエリは次のとおりです-
> db.removeArrayElementsDemo.update( { },{ $pull: { AllPlayerName: "John" }},{multi:true });
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) すべてのドキュメントをもう一度確認しましょう-
> db.removeArrayElementsDemo.find().pretty();
これにより、次の出力が生成されます-
{
"_id" : ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName" : [
"Sam",
"Carol",
"David"
]
}
{
"_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName" : [
"Chris",
"Robert",
"Mike"
]
} -
MongoDB Aggregateを使用して、ドキュメントと配列要素の平均を取得しますか?
このために、$groupおよびaggregate()とともに$avgを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo598.insertOne( ... { ... Information:'Student', ... id:100, ... details:[ ... {Name:'Chris',Ma
-
コレクションから配列全体を削除するMongoDBクエリ?
コレクションから配列全体を削除するには、MongoDBで$unsetを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo609.insertOne({"ListOfSubject":["MySQL","MongoDB"]});{ "acknowledged" : true, "insertedId" : ObjectId("5e974695f57d0dc0b182d62c") } > db.demo609