我有这个集合
[{
"_id" : ObjectId("57a8a6c3c48933256cfd8368"),
"Title" : "T1",
"TitleData" : [
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9b"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96fa7"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96f96"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9c"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9d"),
"Res" : 0
}
]
},
{
"_id" : ObjectId("57a8a6c3c48933256cfd8369"),
"Word" : "T2",
"WordsData" :
[
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9b"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96f96"),
"Res" : 2
}
]
},
{
"_id" : ObjectId("57a8a6c3c48933256cfd8360"),
"Word" : "T3",
"WordsData" :
[
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9b"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96fa7"),
"Res" : 0
}
]
}
]
我需要进行查询以仅提取以下文档:
a)包含在TitleData UserId
=“57a87f5cc48933119cb96f9b”和“57a87f5cc48933119cb96fa7”中
b)2个TitleData元素中至少有一个必须具有MatchType!= 2
所以最终结果将是:
[{
"_id" : ObjectId("57a8a6c3c48933256cfd8360"),
"Title" : "T3",
"TitleData" :
[
{
"UserId" : ObjectId("57a87f5cc48933119cb96f9b"),
"Res" : 2
},
{
"UserId" : ObjectId("57a87f5cc48933119cb96fa7"),
"Res" : 0
}
]
}
]
我可以做的是使用以下指令过滤a)标准的结果:
db.getCollection('collection_name').find({TitleData:{$elemMatch:{UserId:ObjectId("57a87f5cc48933119cb96f9b"),UserId:ObjectId("57a87f5cc48933119cb96fa7")}}})
但我找不到用a)过滤b)条件的方法 有什么建议吗?
[编辑]
这个解决方案对于a)点更好。
db.getCollection('collection_name').find({
$and: [{
TitleData: {
$elemMatch: {
UserId: ObjectId("57a87f5cc48933119cb96f9b")
}
}
},{
TitleData: {
$elemMatch: {
UserId: ObjectId("57a87f5cc48933119cb96fa7")
}
}
},
{
TitleData: {
$elemMatch: {
$ne: {
"Res": 2
}
}
}
}]
}));
答案 0 :(得分:1)
使用$and
:
db.getCollection('collection_name').find({
$and: [{
TitleData: {
$elemMatch: {
UserId: ObjectId("57a87f5cc48933119cb96f9b"),
UserId: ObjectId("57a87f5cc48933119cb96fa7")
}
}
}, {
TitleData: {
$elemMatch: {
$ne: {
"Res": 2
}
}
}
}]
}));
使用您的集合对象从控制台测试输出:
> db.collection.find({ $and: [{ TitleData: { $elemMatch: { UserId: ObjectId("57a87f5cc48933119cb96f9b"), UserId: ObjectId("57a87f5cc48933119cb96fa7") } } },{ TitleData: { $elemMatch: { $ne: { "Res": 2 } } }}]});
{ "_id" : ObjectId("57a8a6c3c48933256cfd8368"), "Title" : "T1", "TitleData" : [ { "UserId" : ObjectId("57a87f5cc48933119cb96f9b"), "Res" : 2 }, { "UserId" : ObjectId("57a87f5cc48933119cb96fa7"), "Res" : 2 }, { "UserId" : ObjectId("57a87f5cc48933119cb96f96"), "Res" : 2 }, { "UserId" : ObjectId("57a87f5cc48933119cb96f9c"), "Res" : 2 }, { "UserId" : ObjectId("57a87f5cc48933119cb96f9d"), "Res" : 0 } ] }
编辑未添加所有控制台输出...