How can I filter by a nested subdocument value ? I need to filter the playlist by the owner id.
如何通过嵌套的子文档值进行筛选?我需要通过所有者ID过滤播放列表。
var playlistSchema = new Schema();
playlistSchema.add({
name: String,
owner: {
id: String,
email: String,
name: String
}
});
2 个解决方案
#1
0
You can use sort() method for filter by ascending order and descending order.
您可以按升序和降序使用sort()方法进行过滤。
Ascending order use follow method.
升序使用跟随方法。
playlist.find().sort('owner.id': 1);
Descending order use follow method.
降序使用跟随方法。
playlist.find().sort('owner.id': -1);
#2
0
Assume a collection sales has the following documents:
假设集合销售具有以下文档:
{
_id: 0,
items: [
{ item_id: 43, quantity: 2, price: 10 },
{ item_id: 2, quantity: 1, price: 240 }
]
}
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110 },
{ item_id: 103, quantity: 4, price: 5 },
{ item_id: 38, quantity: 1, price: 300 }
]
}
{
_id: 2,
items: [
{ item_id: 4, quantity: 1, price: 23 }
]
}
The following example filters the items array to only include documents that have a price greater than or equal to 100:
以下示例将items数组过滤为仅包含价格大于或等于100的文档:
db.sales.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100 ] }
}
}
}
}
])
#1
0
You can use sort() method for filter by ascending order and descending order.
您可以按升序和降序使用sort()方法进行过滤。
Ascending order use follow method.
升序使用跟随方法。
playlist.find().sort('owner.id': 1);
Descending order use follow method.
降序使用跟随方法。
playlist.find().sort('owner.id': -1);
#2
0
Assume a collection sales has the following documents:
假设集合销售具有以下文档:
{
_id: 0,
items: [
{ item_id: 43, quantity: 2, price: 10 },
{ item_id: 2, quantity: 1, price: 240 }
]
}
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110 },
{ item_id: 103, quantity: 4, price: 5 },
{ item_id: 38, quantity: 1, price: 300 }
]
}
{
_id: 2,
items: [
{ item_id: 4, quantity: 1, price: 23 }
]
}
The following example filters the items array to only include documents that have a price greater than or equal to 100:
以下示例将items数组过滤为仅包含价格大于或等于100的文档:
db.sales.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100 ] }
}
}
}
}
])