replaceWith‘可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括‘id‘字段。使用‘replaceWith`可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括`_id`字段。使用`replaceWith‘可以将输入文档替换为指定的文档。该操作可以替换输入文档的所有字段,包括‘id‘字段。使用‘replaceWith还可以将内嵌文档提升到最顶级,也可以把它替换掉。替换文档可以是任何能够解析为文档的有效表达式。
replaceWith‘与‘replaceWith`与`replaceWith‘与‘replaceRoot`有很多相似点,但也有一些不同点。
语法
{
$replaceWith: <replacementDocument> }
使用
如果<replacementDocument>
不是一个文档或者被解析为一个错误的文档(如:文档不存在),都会失败,例如:使用下面的文档创建一个集合:
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" },
])
下面的$replaceWith
会操作失败,因为最后一个文档缺少name
字段:
db.collection.aggregate([
{
$replaceWith: "$name" }
])
要避免上面的错误,可以使用$mergeObjects
把name
文档与某个缺省文档合并,如:
db.collection.aggregate([
{
$replaceWith: {
$mergeObjects: [ {
_id: "$_id", first: "", last: "" }, "$name" ] } }
])
也可以使用$match
阶段,在$replaceWith
之前筛选掉name
字段异常的数据:
db.collection.aggregate([
{
$match: {
name : {
$exists: true, $not: {
$type: "array" }, $type: "object" } } },
{
$replaceWith: "$name" }
])
亦或者使用$ifNull
表达式来指定其它的文档,如:
db.collection.aggregate([
{
$replaceWith: {
$ifNull: [ "$name", {
_id: "$_id", missingName: true} ] } }
])
举例:
替换内嵌文档字段
使用下面的语句创建一个people
集合:
db.people.insertMany([
{
"_id" : 1, "name" : "Arlene", "age" : 34, "pets" : {
"dogs" :