我正在尝试查找已存在的电话号码,如果存在,则向我提供他们的电话号码以及不存在的电话号码。输入我只收到电话号码数组,我需要检查数据库,以确定哪一个存在,哪些不是在这篇文章的底部显示。
用户数据
{
"_id" : "mJPqhyyGoeyfa3p2w",
"createdAt" : ISODate("2015-11-30T22:33:27.649Z"),
"phone" : {
"number" : "123456789",
"verified" : true
}
},
{
"_id" : "dsfsyGoeyfa3p2w",
"createdAt" : ISODate("2015-11-30T22:33:27.649Z"),
"phone" : {
"number" : "+14155553695",
"verified" : true
}
}
考虑到输入[ "123456789", "+14155553695", 10, 20]
db.users.aggregate([
{
'$match': { "phone.number" : { '$in' : [ "123456789", "+14155553695", 10, 20]}}
}
,{
'$project' : {"phone" : "$phone.number"},
}
,{
'$group' : {
"_id" : null,
'phones': {'$push' : '$phone'}
}
}
])
尝试首先实现
{
"result":[
{
"_id":null,
"phones":[
"+14155553695",
"123456789"
],
phoneFoundDetails:[
{
"_id":"xsLSt8cNaggcirxGu",
"phone":"+14155553695"
},
{
"_id":"mJPqhyyGoeyfa3p2w",
"phone":"123456789"
}
],
"ok":1.0000000000000000
}
]
}
最终实现这样的目标
{
"result":[
{
"_id":null,
"notFound":[
"10",
"20"
],
phoneFoundDetails:[
{
"_id":"xsLSt8cNaggcirxGu",
"phone":"+14155553695"
},
{
"_id":"mJPqhyyGoeyfa3p2w",
"phone":"123456789"
}
],
"ok":1.0000000000000000
}
]
}
答案 0 :(得分:0)
你可以这样做以获得你想要的结果:
db.phones.aggregate([
{"$match": { "phone.number" : { "$in" : [ "123456789", "+14155553695", 10, 20]}}},
{'$group' : {
"_id" : null,
"phones": { "$push" : "$phone.number"},
"phoneFoundDetails": {"$push" : {"_id":"$_id" , "phone" : "$phone.number"}}}
}
])
根据您的样本数据,它将返回:
{
"_id" : null,
"phones" : [
"123456789",
"+14155553695"
],
"phoneFoundDetails" : [
{
"_id" : "mJPqhyyGoeyfa3p2w",
"phone" : "123456789"
},
{
"_id" : "dsfsyGoeyfa3p2w",
"phone" : "+14155553695"
}
]
}