我在下面定义了一个数组,它包含一些字符串,
arr = ["hola", "hii", "hey", "namaste"];下面是我在mongodb中的文档
{
"user_id": "Michael",
"list": ["hola", "ola", "hey", "maybe"]
}现在,我想在mongodb中编写一个查询,它返回所有"arr“元素,这些元素也存在于特定"user_id”的“列表”中。
,所以我想要的输出是
_id: "_id" : ObjectId("5828ae4779f2e01b06bb7a61"), results: ["hola", "hey"]我使用聚合编写了下面的查询,但是我得到的错误是
MongoError: FieldPath field names may not start with '$'我的代码
arraymodel.aggregate(
{ $match: { user_id: "Michael" }},
{ $unwind: '$list'},
{ $match: {list: {$in: arr}}},
{ $group: {_id: '$_id', results: {$push: '$list.$'}}},
function(err, docs) {
if (err) {
console.log('Error Finding query results');
console.log(err);
} else {
if (docs) {
console.log('docs: ', docs);
} else {
console.log('No Arr Found');
}
}
}
);发布于 2016-11-16 14:10:39
你可以试试$setIntersection。
db.arrayModel.aggregate(
[{
$match: {
user_id: "Michael"
}
}, {
$project: {
_id: 1,
results: {
$setIntersection: ["$list", ["hola", "hii", "hey", "namaste"]]
}
}
}]
)样本输出
{ "_id" : ObjectId("582c6902a5ff9d6d50e722c3"), "results" : [ "hola", "hey" ] }发布于 2016-11-16 14:15:29
只需去掉{$push: '$list.$'}中的$,就可以得到所需的输出。
以下是完整的查询:
db.collection.aggregate(
{$match:{user_id:"Michael"}},
{$unwind:'$list'},
{$match:{list:{$in:["hola","hey"]}}},
{$group:{_id:"$_id",results:{$push:"$list"}}})https://stackoverflow.com/questions/40633944
复制相似问题