mongodb setdifference之间的集合

时间:2017-09-12 11:05:59

标签: mongodb aggregation-framework

我在mongodb中有以下2个集合

db.test.insert({"Name":"a","keyid":1,"description":"test"})
db.test.insert({"Name":"a","keyid":2,"description":"test"})
db.test.insert({"Name":"a","keyid":3,"description":"test"})
db.test.insert({"Name":"a","keyid":5,"description":"test"})
db.test.insert({"Name":"a","keyid":6,"description":"test"})
db.test.insert({"Name":"b","keyid":3,"description":"test"})
db.test.insert({"Name":"b","keyid":4,"description":"test"})


db.test1.insert({"Name":"a","keyid":1,"description":"test"})
db.test1.insert({"Name":"a","keyid":2,"description":"test"})
db.test1.insert({"Name":"a","keyid":8,"description":"test"})
db.test1.insert({"Name":"a","keyid":5,"description":"test"})
db.test1.insert({"Name":"a","keyid":6,"description":"test"})

我想将test中的文件插入test1,以获取test1中不存在的密钥id和名称,在这种情况下是

db.test1.insert({"Name":"a","keyid":3,"description":"test"})
db.test1.insert({"Name":"b","keyid":3,"description":"test"})
db.test1.insert({"Name":"b","keyid":4,"description":"test"})

和类似我想从test1插入文件来测试测试中不存在的密钥id和名称,在这种情况下是

 db.test.insert({"Name":"a","keyid":8,"description":"test"})

基本上我尝试在2集合

之间执行setdifference

目前我在做

db.test.aggregate([
   {"$group" : {_id : {Name:"$Name", keyid:"$keyid"}}}, 
   {"$project" : { Name:"$_id.Name",keyid:"$_id.keyid"}}
], { allowDiskUse: true })

db.test1.aggregate([
   {"$group" : {_id : {Name:"$Name", keyid:"$keyid"}}}, 
   {"$project" : { Name:"$_id.Name",keyid:"$_id.keyid"}}
], { allowDiskUse: true })

然后执行第一个聚合管道中的输出是否存在于第二个聚合管道的输出中,反之亦然。

使用mongodb中的set操作是否有更好的方法。

0 个答案:

没有答案