我真的是MongoDB或NoSQL資料庫的新手。
我有這樣一個userSchema模式
constpostSchema = {
title: String,
posted_on: 日期const userSchema = {
name: String,
posts: [postSchema]
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我想檢索一個用戶在給定范圍內的帖子(/api/users/:userId/posts?from=date&to=date&limit=limit)使用mongodb查詢。在關系型資料庫中,我們通常會創建兩組不同的表,并使用一些條件查詢第二個表(帖子),然后得到所需的結果。
我們怎樣才能在mongodb中實作同樣的目的?我已經嘗試使用$elemMatch來參考這個,但它似乎不起作用。
uj5u.com熱心網友回復:
使用聚合框架的2種方法,可以比查找做得更多。
使用查找,我們主要是從一個集合中選擇檔案,或者從被選中的檔案中保留一些欄位的專案,但是這里你只需要陣列中的一些成員,所以使用了聚合。
本地方式(在檔案級別的解決方案)沒有解壓等
查詢
- 對陣列進行過濾,只保留posted_on >1和<4 (為了簡單起見,我使用了數字,使用日期也是一樣的)
- 取前2個陣列。
- 取陣列的前2個元素(限制2)
db.collection.aggregate( [
{
"$match"/span>: {
"name": {
"$eq": "n1"。
}
}
},
{
"$set": {
"post": {
"$slice": [
{
"$filter": {
"input": "$posts",
"條件": {
"$and": [
{
"$gt": [
"$this.post_on",
1.
]
},
{
"$lt": [
"$this.post_on",
5.
]
}
]
}
}
},
2
]
}
}
}
])
Uwind 解決方案(集合級別的解決方案
查詢
- 匹配用戶 。
- 解開陣列,并使每個成員都成為ROOT 。
- 匹配日期 >1 <4 。
- limit 2
db.collection.aggregate( [
{
"$match"/span>: {
"name": {
"$eq": "n1"。
}
}
},
{
"$unwind": {
"path": "$posts": "path".
}
},
{
"$replaceRoot": {
"newRoot": "$posts": "newRoot".
}
},
{
"$match": {
"$and": [
{
"posted_on": {
"$gt": 1.
}
},
{
"posted_on": {
"$lt": 5.
}
}
]
}
},
{
"$limit": 2.
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/319837.html
標籤:
