我有一个对象数组
[
{
userId: '541c83d89ff44f767a23c546',
emailArray: [
'abc@amazon.com',
'zxc@amazon.com',
'pqr@amazon.com',
'lol@amazon.com'
]
},
{
userId: '56bd6bf220591a124001d178',
emailArray:[
'mno@gmail.com',
'uvw@gmail.com'
'second@gmail.com'
]
}
]
并为每个userId我想创建MongoDb查询对象,如下所示
var q1 = { $and: [ {userId:userId1}, {"interactions.emailId": {$in:emailArray1}
var q2 = { $and: [ {userId:userId2}, {"interactions.emailId": {$in:emailArray2}
var q3 = { $and: [ {userId:userId3}, {"interactions.emailId": {$in:emailArray3}
.....
var qn = { $and: [ {userId:userId(n)}, {"interactions.emailId": {$in:emailArray(n)}
其中
userId1 = 541c83d89ff44f767a23c546 and userId2 = 56bd6bf220591a124001d178
emailArray1 = [
'abc@amazon.com',
'zxc@amazon.com',
'pqr@amazon.com',
'lol@amazon.com'
]
emailaray2 = [
'mno@gmail.com',
'uvw@gmail.com'
'second@gmail.com'
]
等等。
然后在最后一个finally查询对象
var queryFinal = { $or: [ q1, q2,q3......qn] }
我该怎么做?
答案 0 :(得分:2)
只需使用常规JavaScript:
var data = [
{ userId: '541c83d89ff44f767a23c546',
emailArray:
[ 'abc@amazon.com',
'zxc@amazon.com',
'pqr@amazon.com',
'lol@amazon.com' ]
},
{ userId: '56bd6bf220591a124001d178',
emailArray:
[ 'mno@gmail.com',
'uvw@gmail.com',
'second@gmail.com' ]
}
];
var queryFinal = { "$or": data.map(function(el) {
el["interactions.emailId"] = { "$in": el.emailArray };
delete el.emailArray;
return el;
}) };
所有 MongoDB查询参数已经是“AND”条件,因此您无需在大多数情况下明确声明$and
。
产地:
{
"$or" : [
{
"userId" : "541c83d89ff44f767a23c546",
"interactions.emailId" : {
"$in" : [
"abc@amazon.com",
"zxc@amazon.com",
"pqr@amazon.com",
"lol@amazon.com"
]
}
},
{
"userId" : "56bd6bf220591a124001d178",
"interactions.emailId" : {
"$in" : [
"mno@gmail.com",
"uvw@gmail.com",
"second@gmail.com"
]
}
}
]
}