我在 MongoDB 中遇到与 $in 相关的问题,没有得到想要的结果。
为了更好的可视化,这是我的 MongoDB 收集数据
[
{
"_id" : ObjectId("5aeaf7c73c3e9de82d91e439"),
"companyID" : "4",
"accounts" : [
{
"_id" : ObjectId("5aeaf7c720262a1db759edf5"),
"userID" : "1",
"preferences" : [
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeaf7c720262a1db759edf7"),
"preferenceID" : "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T11:51:35.509Z"),
"updatedAt" : ISODate("2018-05-03T11:51:35.509Z")
},
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeaf7c720262a1db759edf6"),
"preferenceID" : "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T11:51:35.509Z"),
"updatedAt" : ISODate("2018-05-03T11:51:35.509Z")
}
]
}
],
"__v" : 0
},
{
"_id" : ObjectId("5aeafe693c3e9de82d91e43a"),
"companyID" : "5",
"accounts" : [
{
"_id" : ObjectId("5aeafe698b1d5f2057419c99"),
"userID" : "1",
"preferences" : [
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe698b1d5f2057419c9b"),
"preferenceID" : "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:19:53.436Z"),
"updatedAt" : ISODate("2018-05-03T12:19:53.436Z")
},
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe698b1d5f2057419c9a"),
"preferenceID" : "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:19:53.436Z"),
"updatedAt" : ISODate("2018-05-03T12:19:53.436Z")
}
]
}
],
"__v" : 0
},
{
"_id" : ObjectId("5aeafe6d3c3e9de82d91e43b"),
"companyID" : "6",
"accounts" : [
{
"_id" : ObjectId("5aeafe6d8b1d5f2057419c9c"),
"userID" : "1",
"preferences" : [
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe6d8b1d5f2057419c9e"),
"preferenceID" : "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:19:57.331Z"),
"updatedAt" : ISODate("2018-05-03T12:19:57.331Z")
},
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe6d8b1d5f2057419c9d"),
"preferenceID" : "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:19:57.331Z"),
"updatedAt" : ISODate("2018-05-03T12:19:57.331Z")
}
]
},
{
"_id" : ObjectId("5aeafe738b1d5f2057419c9f"),
"userID" : "2",
"preferences" : [
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe738b1d5f2057419ca1"),
"preferenceID" : "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:20:03.987Z"),
"updatedAt" : ISODate("2018-05-03T12:20:03.987Z")
},
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe738b1d5f2057419ca0"),
"preferenceID" : "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:20:03.987Z"),
"updatedAt" : ISODate("2018-05-03T12:20:03.987Z")
}
]
},
{
"_id" : ObjectId("5aeafe778b1d5f2057419ca2"),
"userID" : "3",
"preferences" : [
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe778b1d5f2057419ca4"),
"preferenceID" : "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:20:07.062Z"),
"updatedAt" : ISODate("2018-05-03T12:20:07.062Z")
},
{
"emailNotification" : true,
"smsNotification" : true,
"pushNotification" : false,
"webNotification" : false,
"lastUpdatedBy" : "SYSTEM",
"_id" : ObjectId("5aeafe778b1d5f2057419ca3"),
"preferenceID" : "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt" : ISODate("2018-05-03T12:20:07.062Z"),
"updatedAt" : ISODate("2018-05-03T12:20:07.062Z")
}
]
}
],
"__v" : 0
}]
我想从数据中得到什么。 我正在尝试根据公司 ID 和用户 ID 获取每家公司的用户偏好,但针对多个公司和多个用户,而不是针对单个用户。
举个例子,我有这个输入数据 [userID:2,companyID: 6] 和 [userID:1 , companyID:4]
基于上面添加的文档数据的输出,应该是
[
{
"userID":2,
"companyID":6,
"preferences":[] // the preferences from that db
},
{
"userID":1,
"companyID":4,
"preferences":[] // their respective preferences array
}
]
上面是期望的输出,现在我的解决方法
方法
我正在获取对象数组形式的输入参数,就像这样
input_json = [{
"userID":2,
"companyID":6
},
{
"userID":1,
"companyID":4
},
]
获取输入 JSON 后,我制作了两个不同的数组,用户数组、公司数组,user_array 将保存所有用户 ID,company_array 将保存所有像这样的公司ID
user_array = input_json.map((elem)=>elem.userID) // which will hold all the company ID
//For the above input_json, the value of `user_array` would be
// `user_array: [2,1]`
company_array = input_json.map((elem)=>elem.userID)
//For the above input_json, the value of `company_array` would be
// `company_array`:[4,4]
在我分别获得 userIDs 和 companyID 的值后,我使用 $in 在 MongoDB 上触发查询以匹配数组中的 id
db.collection.find({
userID:{
$in:user_array
},
accounts.companyID:{
$in:company_array
}
})
我没有得到想要的结果,我希望将 userID 和 companyID 用作获取数据的唯一键。
但是发生的事情是匹配 user_array 中的 userID 和 company_array 中的 companyID。但是,我想要 userID 和 companyID 要检查以获取数据。
任何帮助将不胜感激:)
最佳答案
只是对您的示例进行了一些扩展,以包括您的请求数组实际上要求来自同一公司的多个用户的“可能”情况。
基本的“查询”条件只是输入数组的重新映射并在 $or 中使用它查询参数。结果如下:
{
"$or": [
{
"companyID": "6",
"accounts.userID": "3"
},
{
"companyID": "6",
"accounts.userID": "2"
},
{
"companyID": "4",
"accounts.userID": "1"
}
]
}
这将匹配您的“文档”,但相应的“用户”信息包含在 “accounts” 数组中。为了只检索那些项目,我们需要应用 $filter条件只是让那些数组条目符合条件。然后它真的只是在剩余的数组内容上使用 $unwind 和一个小文档 reshape 以使用 $project 放入所需的输出格式的问题。 .
整个生成的语句如下:
Company.aggregate([
{ '$match': {
'$or': [
{ companyID: '6', 'accounts.userID': '3' },
{ companyID: '6', 'accounts.userID': '2' },
{ companyID: '4', 'accounts.userID': '1' }
]
}},
{ '$addFields': {
accounts: {
'$filter': {
input: '$accounts',
cond: {
'$or': [
{ '$and': [
{ '$eq': [ '$companyID', '6' ] },
{ '$eq': [ '$$this.userID', '3' ] }
] },
{ '$and': [
{ '$eq': [ '$companyID', '6' ] },
{ '$eq': [ '$$this.userID', '2' ] }
] },
{ '$and': [
{ '$eq': [ '$companyID', '4' ] },
{ '$eq': [ '$$this.userID', '1' ] }
] }
]
}
}
}
}},
{ '$unwind': '$accounts' },
{ '$project': {
userID: '$accounts.userID',
companyID: 1,
preferences: '$accounts.preferences'
}}
])
$or的内容用于查询和附加形式 $or对于$filter基本上是从输入数组生成的,如下所示:
let query = {
$or: input.map(({ userID, companyID }) =>
({ companyID, 'accounts.userID': userID }))
};
let condition = input.map(({ userID, companyID }) =>
({ "$and": [
{ "$eq": ["$companyID", companyID] },
{ "$eq": ["$$this.userID", userID] }
]})
);
然后在管道构造的其余部分中用作参数,这大部分是静态的。注意 $filter 中的用法因为 "cond" 需要“聚合逻辑运算符”,它根据测试的内容返回一个 bool 值。因此它们在形式上不同于查询运算符。
相同的“配对”适用于每个 $or 条件,因此 “companyID” 值以及当前 “userID” 在查找与该组合的匹配项时,会考虑帐户数组中的值。 $filter内从数组外部检查 "companyID" 很重要,同时还要检查当前数组元素。
我们不能用标准 positional $ operator 做到这一点的原因投影本质上是因为 $or查询中的条件。这里为了演示添加了“多重匹配”的附加约束,但是由于 $or在查询中,MongoDB 无法确定“条件集”中的哪一个实际上满足任何单个文档的元素匹配位置。
因此,如果您希望每个公司匹配“一个”用户或“多个”用户,这并不重要,因为无论如何都需要应用相同的聚合过滤器才能提取正确的“用户”详细信息。
完整的演示 list 如下:
const { Schema } = mongoose = require('mongoose');
const uri = 'mongodb://localhost/test';
mongoose.Promise = global.Promise;
mongoose.set('debug',true);
let input = [
{
"userID": 3,
"companyID": 6
},
{
"userID": 2,
"companyID": 6
},
{
"userID": 1,
"companyID": 4
}
];
// non-strict for testing
const Company = mongoose.model('Company', new Schema({},{ strict: false }));
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri);
// Clean data to actually be matching strings
input = input.map(({ userID, companyID }) =>
({ userID: userID.toString(), companyID: companyID.toString() }));
let query = {
$or: input.map(({ userID, companyID }) =>
({ companyID, 'accounts.userID': userID }))
};
log(query);
let condition = input.map(({ userID, companyID }) =>
({ "$and": [
{ "$eq": ["$companyID", companyID] },
{ "$eq": ["$$this.userID", userID] }
]})
);
log(condition);
let result = await Company.aggregate([
{ "$match": query },
{ "$addFields": {
"accounts": {
"$filter": {
"input": "$accounts",
"cond": { "$or": condition }
}
}
}},
{ "$unwind": "$accounts" },
{ "$project": {
"userID": "$accounts.userID",
"companyID": 1,
"preferences": "$accounts.preferences"
}}
]);
log(result);
mongoose.disconnect();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
这给出了如下输出:
[
{
"_id": "5aeaf7c73c3e9de82d91e439",
"companyID": "4",
"userID": "1",
"preferences": [
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeaf7c720262a1db759edf7",
"preferenceID": "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T11:51:35.509Z",
"updatedAt": "2018-05-03T11:51:35.509Z"
},
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeaf7c720262a1db759edf6",
"preferenceID": "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T11:51:35.509Z",
"updatedAt": "2018-05-03T11:51:35.509Z"
}
]
},
{
"_id": "5aeafe6d3c3e9de82d91e43b",
"companyID": "6",
"userID": "2",
"preferences": [
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeafe738b1d5f2057419ca1",
"preferenceID": "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T12:20:03.987Z",
"updatedAt": "2018-05-03T12:20:03.987Z"
},
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeafe738b1d5f2057419ca0",
"preferenceID": "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T12:20:03.987Z",
"updatedAt": "2018-05-03T12:20:03.987Z"
}
]
},
{
"_id": "5aeafe6d3c3e9de82d91e43b",
"companyID": "6",
"userID": "3",
"preferences": [
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeafe778b1d5f2057419ca4",
"preferenceID": "6fbd6c-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T12:20:07.062Z",
"updatedAt": "2018-05-03T12:20:07.062Z"
},
{
"emailNotification": true,
"smsNotification": true,
"pushNotification": false,
"webNotification": false,
"lastUpdatedBy": "SYSTEM",
"_id": "5aeafe778b1d5f2057419ca3",
"preferenceID": "6fb118-4c56-11e8-842f-0ed5f89f718b",
"createdAt": "2018-05-03T12:20:07.062Z",
"updatedAt": "2018-05-03T12:20:07.062Z"
}
]
}
]
这表明我们只返回了文档中匹配的公司和用户详细信息组合。
NOTE Not sure if with the input sample you gave it was "intentional" that the values are given as "numeric" and not as "strings", where of course they are actually "strings" in the data it needs to match to. There's a simple line of code which is converting the numeric values to strings, which of course is not necessary where both your input types and stored types match already.
Also whilst mongoose would typically "cast" these values under normal query operations to whatever was in the schema, this does not happen with aggregation pipelines. Any conditions you apply for matching within the aggregation pipeline operations requires "you" to cast values to the correct type yourself.
Mongoose does not do this because it cannot make the "presumption" during an aggregation pipeline stage that the data presented at the time is in the same state as what the schema knows about. Aggregation operations are typically about "reshaping documents", and for this reason "schema" does not apply here.
关于node.js - 在 MongoDB 中的多个字段上使用 $in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152422/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。