Docs Menu
Docs Home
/
MongoDB マニュアル
/ / /

$unset(集計)

項目一覧

  • 定義
  • 構文
  • Considerations

注意

曖昧さ回避

次のページでは、集計ステージ $unsetについて説明しています。 更新演算子 $unsetについて詳しくは、 $unsetを参照してください。

$unset

ドキュメントからフィールドを削除または除外します。

$unsetステージの構文は次のとおりです。

  • 単一のフィールドを削除するには、 $unsetは、削除するフィールドを指定する string を受け取ります。

    { $unset: "<field>" }
  • 複数のフィールドを排除するために、$unset は排除するフィールドの配列を受け取ります。

    { $unset: [ "<field1>", "<field2>", ... ] }

$unset は、フィールドを排除/除外する$project ステージのエイリアスです。

{ $project: { "<field1>": 0, "<field2>": 0, ... } }

埋め込みドキュメント内の 1 つまたは複数のフィールドを排除/除外するには、次のようにドット表記を使用できます。

{ $unset: "<field.nestedfield>" }

or

{ $unset: [ "<field1.nestedfield>", ...] }

次のドキュメントを使用してサンプルbooks コレクションを作成します。

db.books.insertMany([
{ "_id" : 1, title: "Antelope Antics", isbn: "0001122223334", author: { last:"An", first: "Auntie" }, copies: [ { warehouse: "A", qty: 5 }, { warehouse: "B", qty: 15 } ] },
{ "_id" : 2, title: "Bees Babble", isbn: "999999999333", author: { last:"Bumble", first: "Bee" }, copies: [ { warehouse: "A", qty: 2 }, { warehouse: "B", qty: 5 } ] }
])

次の例えでは、最上位のフィールド copies を排除します。

db.books.aggregate([ { $unset: "copies" } ])

または、次の構文を使用することもできます。

db.books.aggregate([ { $unset: [ "copies" ] } ])

どちらの操作でも、次のドキュメントが返されます。

{ "_id" : 1, "title" : "Antelope Antics", "isbn" : "0001122223334", "author" : { "last" : "An", "first" : "Auntie" } }
{ "_id" : 2, "title" : "Bees Babble", "isbn" : "999999999333", "author" : { "last" : "Bumble", "first" : "Bee" } }

次の例えでは、最上位のフィールド isbncopies を排除します。

db.books.aggregate([
{ $unset: [ "isbn", "copies" ] }
])

$unset操作により、次のドキュメントが出力されます。

{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An", "first" : "Auntie" } }
{ "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble", "first" : "Bee" } }

次の例えでは、最上位フィールドの isbn、埋め込みフィールドの firstname ドキュメントから)、および埋め込みフィールドの warehousecopies 配列の要素から)を排除します。

db.books.aggregate([
{ $unset: [ "isbn", "author.first", "copies.warehouse" ] }
])

$unset操作により、次のドキュメントが出力されます。

{ "_id" : 1, "title" : "Antelope Antics", "author" : { "last" : "An" }, "copies" : [ { "qty" : 5 }, { "qty" : 15 } ] }
{ "_id" : 2, "title" : "Bees Babble", "author" : { "last" : "Bumble" }, "copies" : [ { "qty" : 2 }, { "qty" : 5 } ] }

戻る

$unionWith