Yaz*_* IO 1 mongoose mongodb node.js
用户集合
user : {
"_id" : md5random,
"nickname" : "j1",
"name" : "jany"
}
user : {
"_id" : md5random,
"nickname" : "j2",
"name" : "jenneffer"
}
Run Code Online (Sandbox Code Playgroud)
友谊集合
friendship : {
"_id" : md5rand,
"nick1" : "j1",
"nick2" : "j2",
"adTime" : date
}
Run Code Online (Sandbox Code Playgroud)
例如SQL
SELECT friendship.adTime, user.name
FROM friendship
INNER JOIN user ON
(user.nickname=friendship.nick1 or user.nickname=friendship.nick2)
Run Code Online (Sandbox Code Playgroud)
MONGO中是否有任何方法可以获得此SQL结果?
我想得到的结果,我知道mongo不支持这个请求.但这个更好的解决方案是什么?任何人都可以为我写一个例子吗?
MongoDB是面向文档的,而不是关系数据库.所以它没有像sql这样的查询语言.因此,您应该更改数据库架构.
这是一个例子:
定义您的架构.你不能像在sql数据库中那样在mongodb中保存关系.所以直接将朋友添加到用户.要为这些关系添加属性,您必须创建一个新模型(此处:) Friend.
var userSchema = mongoose.Schema({
nickname: String,
name: String,
friends: [{type: mongoose.Schema.Types.ObjectId, ref: 'Friend'}]
});
var friendSchema = mongoose.Schema({
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
addTime: Date
});
var User = mongoose.Model('User', userSchema);
var Friend = mongoose.Model('Friend', friendSchema);
Run Code Online (Sandbox Code Playgroud)获取所有内容addTimes的查询可能如下所示:
User.find().populate('friends').exec(function(err, users) {
if (err) throw err;
var adTimes = [];
users.forEach(function(user) {
user.friends.forEach(function(friend) {
adTimes.push(friend.adTime);
});
});
response.send(adTimes); // adTimes should contain all addTimes from his friends
});
Run Code Online (Sandbox Code Playgroud)
注意:上面的模式应该可以工作,但也许你应该使用关系(如MySQL)或图形数据库(如Neo4j),而不是像面向文档一样MongoDB.
| 归档时间: |
|
| 查看次数: |
10050 次 |
| 最近记录: |