我有这个“用户”集合,其中包括以下文件:
{
"_id" : ObjectId("5bd45a34af6df9a28e6e59a9"),
"name" : "Jo",
"txHistory" : [
{
"_id" : ObjectId("5bd45a34af6df9a28e6e59aa"),
"date" : ISODate("2018-10-27T12:29:40.830Z"),
"from" : "Mary",
"to" : "Jo",
"credit" : 960,
"balance" : 960
},
{
"_id" : ObjectId("5bd45aa4af6df9a28e6e59b2"),
"date" : ISODate("2018-10-27T12:31:32.369Z"),
"from" : "Pat",
"to" : "Jo",
"credit" : 30,
"balance" : 990
},
{
"_id" : ObjectId("5bd45afaaf6df9a28e6e59b4"),
"date" : ISODate("2018-10-27T12:32:58.584Z"),
"from" : "Jo",
"to" : "Pat",
"debit" : 34,
"balance" : 956
},
{
"_id" : ObjectId("5bd45ba9af6df9a28e6e59b8"),
"date" : ISODate("2018-10-27T12:35:53.825Z"),
"from" : "jo",
"to" : "Mary",
"debit" : 10,
"balance" : 946
},
{ ... 1000s more txHistory-Array entries ... }
],
"__v" : 0
},
{ ... 1000s more documents of users ... }
我想在Mongo DB数据库中查询一个用户(“ Jo”),以便可以从txHistory中获得仅包含这些对象的对象,其中:
以显示三个最近收到的交易(玛丽的交易除外)
我很努力地将它们融合在一起,欢迎大家提出解决方案。
非常感谢 PAV
答案 0 :(得分:0)
您可以执行以下操作:
db.users.find({
$and: [{ "txHistory.to": "Jo" },
{ "txHistory.from": { $ne: 'Mary' } }
]
})
.sort({ "txHistory.date": -1 })
.limit(3)