$ merge仅保存一个文档,而不是所有获取的文档:mongodb

时间:2020-02-19 10:36:56

标签: node.js mongodb aggregation-framework

这是我的查询

PessimisticLockException

因此,没有 db.orders.aggregate([ { '$match': { 'date': ISODate("2020-02-11T18:30:00Z") }}, { '$unwind': { 'path': '$orders', }}, { $lookup: { from: 'retailprice', let: { productCode: '$orders.productCode' }, pipeline: [ { $match: { frequency: 'FR', $expr: { $eq: ["$productCode", "$$productCode"] } } } ], as: 'retailprices' } }, { '$unwind': '$retailprice' }, { $lookup: { from: 'discounts', let: { productCode: '$orders.productCode' }, pipeline: [ { $match: { frequency: 'FR', $expr: { $eq: ["$productCode", "$$productCode"] } } } ], as: 'discounts' }}, { '$unwind': '$discounts' }, { '$project':{ 'productCode':'$orders.productCode' , 'vendorId':'$vendorId', 'dealerId':'$dealerId', 'quantity':'$orders.quantity' } },{'$merge':'test'} ]).pretty() 的查询的输出为:

{'$merge':'test'}

但是当我使用 { "_id" : ObjectId("5e3a710af2657521e8c5668a"), "productCode" : "TCE1", "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"), "dealerId" : ObjectId("5e1d82156a67173cb877f67d"), "quantity" : 30, } { "_id" : ObjectId("5e3a710af2657521e8c5668a"), "productCode" : "ECE1", "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"), "dealerId" : ObjectId("5e1d82156a67173cb877f67d"), "quantity" : 67, } 将输出保存到新集合中时,它仅保存了一个文档,即:

{'$merge':'test'}

现在为什么?我假设是因为如果检查了查询输出,两个文档中的{ "_id" : ObjectId("5e3a710af2657521e8c5668a"), "dealerId" : ObjectId("5e1d82156a67173cb877f67d"), "productCode" : "ECE1", "quantity" : 67, "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07") } 是相同的,如果可以的话,该如何解决。如何使用"_id":ObjectId("5e3a710af2657521e8c5668a")保存两个文档,我不想使用$merge,因为无论何时再次运行查询,它都会替换整个文档,或者我该如何将所有提取的文档保存到新文档中集合

1 个答案:

答案 0 :(得分:0)

考虑_id问题时,您假设是正确的:$ unwind阶段为每个数组元素生成一个文档,所有文档都具有相同的_id(与其他字段一样,从原始文档复制) 诀窍是...非常简单!在您的$ project阶段添加“ _id”:0。然后mongodb将create a new _id插入$ merge。

...
        {
                '$project':{
                '_id':0,
                'productCode':'$orders.productCode' ,
                'vendorId':'$vendorId',
                'dealerId':'$dealerId',
                'quantity':'$orders.quantity'
                } 
        },
...

但是请注意,通过这种方式,mongoDB将始终创建新的插入,并且永远不会更新现有的插入。如果您需要更精确的行为,请检查$merge的可选属性