定義
$replaceRoot入力ドキュメントを指定したドキュメントで置き換えます。この操作により、
_idフィールドを含む入力ドキュメント内の既存のフィールドがすべて置き換えられます。既存の埋め込みドキュメントを最上位に引き上げるか、新しいドキュメントを作成して引き上げます(例を参照してください)。注意
You can also use the
$replaceWithstage. The$replaceWithstage peforms the same action as the$replaceRootstage, but the stages have different forms.The
$replaceRootstage has the following form:{ $replaceRoot: { newRoot: <replacementDocument> } } 置換用ドキュメントには、有効な式に変換される任意のドキュメントが利用できます。
<replacementDocument>がドキュメントでない場合、ステージはエラーとなり失敗します。 式の詳細については、「式 」を参照してください。
動作
If the <replacementDocument> is not a document, $replaceRoot errors and fails.
If the <replacementDocument> resolves to a missing document (i.e. the document does not exist), $replaceRoot errors and fails. For example, create a collection with the following documents:
db.collection.insertMany([ { "_id": 1, "name" : { "first" : "John", "last" : "Backus" } }, { "_id": 2, "name" : { "first" : "John", "last" : "McCarthy" } }, { "_id": 3, "name": { "first" : "Grace", "last" : "Hopper" } }, { "_id": 4, "firstname": "Ole-Johan", "lastname" : "Dahl" }, ])
Then the following $replaceRoot operation fails because one of the documents does not have the name field:
db.collection.aggregate([ { $replaceRoot: { newRoot: "$name" } } ])
エラーを回避するには、$mergeObjects を使用して name ドキュメントを次に挙げるような何らかのデフォルト ドキュメントにマージします。
db.collection.aggregate([ { $replaceRoot: { newRoot: { $mergeObjects: [ { _id: "$_id", first: "", last: "" }, "$name" ] } } } ])
[ { _id: 1, first: 'John', last: 'Backus' }, { _id: 2, first: 'John', last: 'McCarthy' }, { _id: 3, first: 'Grace', last: 'Hopper' }, { _id: 4, first: '', last: '' } ]
Alternatively, you can skip the documents that are missing the name field by including a $match stage to check for existence of the document field before passing documents to the $replaceRoot stage:
db.collection.aggregate([ { $match: { name : { $exists: true, $not: { $type: "array" }, $type: "object" } } }, { $replaceRoot: { newRoot: "$name" } } ])
[ { first: 'John', last: 'Backus' }, { first: 'John', last: 'McCarthy' }, { first: 'Grace', last: 'Hopper' } ]
または、$ifNull 式を使用して、次に挙げるような他のドキュメントをルートに指定しても構いません。
db.collection.aggregate([ { $replaceRoot: { newRoot: { $ifNull: [ "$name", { _id: "$_id", missingName: true} ] } } } ])
[ { first: 'John', last: 'Backus' }, { first: 'John', last: 'McCarthy' }, { first: 'Grace', last: 'Hopper' }, { _id: 4, missingName: true } ]
例
$replaceRoot 埋め込みドキュメントフィールドの場合
people という名前のコレクションには次のドキュメントが含まれています。
db.people.insertMany([ { "_id" : 1, "name" : "Arlene", "age" : 34, "pets" : { "dogs" : 2, "cats" : 1 } }, { "_id" : 2, "name" : "Sam", "age" : 41, "pets" : { "cats" : 1, "fish" : 3 } }, { "_id" : 3, "name" : "Maria", "age" : 25 } ])
The following operation uses the $replaceRoot stage to replace each input document with the result of a $mergeObjects operation. The $mergeObjects expression merges the specified default document with the pets document.
db.people.aggregate( [ { $replaceRoot: { newRoot: { $mergeObjects: [ { dogs: 0, cats: 0, birds: 0, fish: 0 }, "$pets" ] } } } ] )
[ { dogs: 2, cats: 1, birds: 0, fish: 0 }, { dogs: 0, cats: 1, birds: 0, fish: 3 }, { dogs: 0, cats: 0, birds: 0, fish: 0 } ]
$replaceRoot 配列にネストされたドキュメントの場合
students という名前のコレクションには次のドキュメントが含まれています。
db.students.insertMany([ { "_id" : 1, "grades" : [ { "test": 1, "grade" : 80, "mean" : 75, "std" : 6 }, { "test": 2, "grade" : 85, "mean" : 90, "std" : 4 }, { "test": 3, "grade" : 95, "mean" : 85, "std" : 6 } ] }, { "_id" : 2, "grades" : [ { "test": 1, "grade" : 90, "mean" : 75, "std" : 6 }, { "test": 2, "grade" : 87, "mean" : 90, "std" : 3 }, { "test": 3, "grade" : 91, "mean" : 85, "std" : 4 } ] } ])
次の操作では、90 以上の grade フィールドを持つ埋め込みドキュメントが最上位レベルに引き上げられます。
db.students.aggregate( [ { $unwind: "$grades" }, { $match: { "grades.grade" : { $gte: 90 } } }, { $replaceRoot: { newRoot: "$grades" } } ] )
[ { test: 3, grade: 95, mean: 85, std: 6 }, { test: 1, grade: 90, mean: 75, std: 6 }, { test: 3, grade: 91, mean: 85, std: 4 } ]
$replaceRoot 新しく作成したドキュメントの場合
$replaceRoot ステージの一部として新しいドキュメントを作成し、そのドキュメントを使用して他のすべてのフィールドを置き換えることもできます。
contacts という名前のコレクションには次のドキュメントが含まれています。
db.contacts.insertMany([ { "_id" : 1, "first_name" : "Gary", "last_name" : "Sheffield", "city" : "New York" }, { "_id" : 2, "first_name" : "Nancy", "last_name" : "Walker", "city" : "Anaheim" }, { "_id" : 3, "first_name" : "Peter", "last_name" : "Sumner", "city" : "Toledo" } ])
次の操作では、first_name フィールドと last_name フィールドから新しいドキュメントを作成します。
db.contacts.aggregate( [ { $replaceRoot: { newRoot: { full_name: { $concat : [ "$first_name", " ", "$last_name" ] } } } } ] )
[ { full_name: 'Gary Sheffield' }, { full_name: 'Nancy Walker' }, { full_name: 'Peter Sumner' } ]
$replaceRoot により、$$ROOT とデフォルト ドキュメントから作成された新しいドキュメントでルートを置換
contacts という名前のコレクションには次のドキュメントが含まれています。
db.contacts.insertMany( [ { "_id" : 1, name: "Fred", email: "fred@example.net" }, { "_id" : 2, name: "Frank N. Stine", cell: "012-345-9999" }, { "_id" : 3, name: "Gren Dell", home: "987-654-3210", email: "beo@example.net" } ] )
The following operation uses $replaceRoot with $mergeObjects to output current documents with default values for missing fields:
db.contacts.aggregate( [ { $replaceRoot: { newRoot: { $mergeObjects: [ { _id: "", name: "", email: "", cell: "", home: "" }, "$$ROOT" ] } } } ] )
[ { _id: 1, name: 'Fred', email: 'fred@example.net', cell: '', home: '' }, { _id: 2, name: 'Frank N. Stine', email: '', cell: '012-345-9999', home: '' }, { _id: 3, name: 'Gren Dell', email: 'beo@example.net', cell: '', home: '987-654-3210' } ]
このページのC#の例では、Atlasサンプルデータセット の sample_mflixデータベースを使用します。MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 MongoDB .NET/ C#ドライバーのドキュメントの「 開始 」を参照してください。
次の Movie クラスは、sample_mflix.movies コレクション内のドキュメントをモデル化します。
[] public class Movie { [] public ObjectId Id { get; set; } [] public string Title { get; set; } = null!; [] public int? Year { get; set; } [] public int? Runtime { get; set; } [] public string? Rated { get; set; } [] public int Metacritic { get; set; } [] public string? Plot { get; set; } [] public string? Type { get; set; } [] public string[]? Cast { get; set; } [] public string[]? Directors { get; set; } [] public string[]? Writers { get; set; } [] public ImdbData? Imdb { get; set; } }
次の ImdbData クラスは、埋め込まれた imdb ドキュメントをモデル化します。
[] public class ImdbData { [] public int? ImdbId { get; set; } [] public double? Rating { get; set; } [] public int? Votes { get; set; } }
To use the MongoDB .NET/C# driver to add a $replaceRoot stage to an aggregation pipeline, call the UnionWith() method on a PipelineDefinition object.
次の例では、imdb フィールドを持つ Movie ドキュメントをフィルターし、タイトルでソートし、結果を 5 ドキュメントに制限し、各ドキュメントを埋め込まれた ImdbData ドキュメントで置き換えるパイプライン ステージを作成します。
var pipeline = new EmptyPipelineDefinition<Movie>() .Match(Builders<Movie>.Filter.Exists(m => m.Imdb)) .Sort(Builders<Movie>.Sort.Ascending(m => m.Title)) .Limit(5) .ReplaceRoot(m => m.Imdb);
このページのNode.js の例では、Atlasサンプルデータセット の sample_mflixデータベースを使用します。無料のMongoDB Atlas cluster を作成し、サンプルデータセットをロードする方法については、 MongoDB Node.jsドライバーのドキュメントの開始を参照してください。
MongoDB Node.jsドライバーを使用して $replaceRoot ステージを集計パイプラインに追加するには、パイプラインオブジェクトで $replaceRoot 演算子を使用します。
次の例では、各入力 movie ドキュメントをその imdb プロパティに保存されているドキュメントに置き換えるパイプラインステージを作成します。次に、この例は集計パイプラインを実行します。
const pipeline = [{ $replaceRoot: { newRoot: "$imdb" } }]; const cursor = collection.aggregate(pipeline); return cursor;
詳細
To learn more about related pipeline stages, see the $replaceRoot guide.